在最后出现的程序中,我得到了这样的输出。
constructor is called
destructor is called
destructor is called
destructor is called
destructor is called
destructor is called
destructor is called
如果因为对析构函数的五次调用,我能够弄清楚最后五行调用了析构函数。但我无法理解前两行。为什么构造函数只被调用一次,然后在下一行调用析构函数。
请解释一下。谢谢
class A {
public :
string name;
int age;
A(){ cout << "constructor is called" << endl; }
~A() { cout << "destructor is called"<< endl; }
};
int main()
{
vector<class A> vec(5);
cout << vec.size() << endl;
return 0;
}
最佳答案
您的默认构造函数只构造了一个对象,然后将其复制了 5 次。添加:
A(const A&) { cout << "copy-constructor is called" << endl; }
通过复制初始对象查看其他对象的创建时间/位置。
关于c++ - 为什么在创建一个vector<A>时,类A的构造函数和析构函数只调用一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18793301/