std :: vector构造函数是否不为每个元素调用对象构造函数?

Mat*_*att 4 c++

我的代码类似于这些内容.

class A
{
  public:
    A(int i) { printf("hello %d\n", i); }
    ~A() { printf("Goodbye\n"); }
}


std::vector(10, A(10));
Run Code Online (Sandbox Code Playgroud)

我注意到hello打印出一次.这似乎意味着向量只为元素分配空间,但不构造它.如何构建10个A对象?

Seb*_*anK 12

当你将它传递给std :: vector时,该对象只构造一次.然后将此对象复制10次.您必须在复制构造函数中执行printf才能看到它.


Let*_*_Be 6

你忘记了复制构造函数:

#include <iostream>
#include <vector>
using namespace std;

class A
{
        int i;
public:
        A(int d) : i(d) { cout << "create i=" << i << endl; }
        ~A() { cout << "destroy" << endl; }
        A(const A& d) : i(d.i) { cout << "copy i=" << d.i << endl; }
};

int main()
{
        vector<A> d(10,A(10));
}
Run Code Online (Sandbox Code Playgroud)

输出:

create i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
Run Code Online (Sandbox Code Playgroud)