c++ - 为什么在创建一个vector<A>时,类A的构造函数和析构函数只调用一次?

标签 c++ stl

在最后出现的程序中,我得到了这样的输出。

   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/

相关文章:

c++ - 无法理解 C++ STL 中的配对如何工作?

c++ - getElementsBytagName 不适用于 DomDocument60

c++ - 从 num1 到 num2 的最短路径(在 C++ 中)

c++ - 将 unsigned char 数组解释为 bool 数组

c++ - 使用 STL 数字的意外参数传递顺序

c++ - 使用 auto 推导的 lambda 成员函数模板

c++ - 除了静态库本身之外,停止 cmake target_link_libraries 链接静态库的两个目标文件

C++ 错误 : request for member 'push_back' in 'v'

c++ - 如何在类中使用 unique 函数?

c++ - std::set<myClass*> 已排序