Home  >  Q&A  >  body text

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

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

#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中吗, 怎么说也只有一次拷贝构造, 为什么会有两次呢?

巴扎黑巴扎黑2764 days ago525

reply all(1)I'll reply

  • 阿神

    阿神2017-04-17 14:02:50

    x{s} calls vector( std::initializer_list<T> init, const Allocator& alloc = Allocator() );, here you first need to construct a std::initializer_list<T>, {s} is to construct a std::initializer_list<T>, and then use this std::initializer_list<T> to construct the vector, so here The copy constructor was called twice

    reply
    0
  • Cancelreply