c++中关于列表初始化vector的问题

浏览:44日期:2023-04-25

问题描述

为了看一下列表初始化时发生了什么, 我写了如下代码:

#ifndef SCREEN_H#define SCREEN_H#include <iostream>class Screen {public: static int x; int y; Screen() {y = ++x;std::cout << 'chuangj ' << y << std::endl; } Screen(const Screen& s) {y = ++x;std::cout << 'kaobei ' << y << std::endl; } ~Screen() {std::cout << 'xigou ' << y << std::endl; }};int Screen::x = 0;#endif // !SCREEN_H

#include <vector>#include 'Screen.h'int main(int argc, char* argv[]) { Screen s = Screen(); std::vector<Screen> x{ s }; std::cout << '第八行' << std::endl; x = {}; std::cout << 'over' << std::endl; return 0;}

输出结果很奇怪 :

chuangj 1kaobei 2kaobei 3xigou 2第八行xigou 3overxigou 1请按任意键继续. . .

也就是说std::vector<Screen> x{ s };这里居然有两次拷贝构造发生, 不是只需要将s拷贝到vector中吗, 怎么说也只有一次拷贝构造, 为什么会有两次呢?

问题解答

回答1:

x{s} 调用的是 vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );,在这里首先你要用构造一个std::initializer_list<T>,{s}这个就是构造一个std::initializer_list<T>,然后再用这个std::initializer_list<T>去构造这个vector,所以这里调用了两次拷贝构造

相关文章: