为了看一下列表初始化时发生了什么, 我写了如下代码:
#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 1
kaobei 2
kaobei 3
xigou 2
第八行
xigou 3
over
xigou 1
请按任意键继续. . .
也就是说std::vector<Screen> x{ s };
这里居然有两次拷贝构造发生, 不是只需要将s拷贝到vector中吗, 怎么说也只有一次拷贝构造, 为什么会有两次呢?
x{s}
callsvector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );
, here you first need to construct astd::initializer_list<T>
, {s} is to construct astd::initializer_list<T>
, and then use thisstd::initializer_list<T>
to construct the vector, so here The copy constructor was called twice