c++ - 析构函数调用的次数比我预期的多

标签 c++ oop constructor output destructor

这是我的最小示例:

#include <iostream>
#include <vector>

class A {
public:
    A() { std::cout << "Constructor\n"; }
    ~A() { std::cout << "Destructor\n"; }
};

class B {
public:
    B() { v.push_back(A()); v.push_back(A()); }
private:
    std::vector<A> v;
};

int main() {
    B b;
    return 0;
}

所以,我得到了这个输出:

Constructor   // first push back
Destructor    // copy destroyed
Constructor   // second push back
Destructor    // copy destroyed
Destructor    // ???????????????
// B object goes out of scope and its vector too...
Destructor    // v[0] destructor called 
Destructor    // v[1] destructor called 

有人可以解释一下吗?


在关注 Dave 的评论之后:

Constructor
Copy constructor
Destructor
Constructor
Copy constructor
Copy constructor
Destructor
Destructor
Destructor
Destructor

最佳答案

添加一个重载的复制构造函数和一些指示正在对哪个对象进行操作的指示器可以阐明这种情况:

#include <iostream>
#include <vector>

class A {
public:
    A(unsigned i): i(i) { std::cout << "Constructor " << i << std::endl; }
    A(const A& a) : i(a.i) { std::cout << "Copy constructor " << i << std::endl; }
    ~A() { std::cout << "Destructor " << i << std::endl; }
    unsigned i;
};

class B {
public:
    B() { v.push_back(A(0)); v.push_back(A(1)); }
private:
    std::vector<A> v;
};

int main() {
    B b;
    return 0;
}

在第一次推送时,我们复制并销毁临时文件。在第二次推送时,我们制作一个拷贝,然后复制第一个对象,然后销毁第一个对象和临时对象。最后,我们销毁这两个对象。

我猜想 std::vector 最初分配的容量为 1,所以第二次推送强制重新分配?如果我强制使用更大的初始容量(通过在第一次推送之前调用 v.reserve(5)),那么额外的拷贝就会消失。

关于c++ - 析构函数调用的次数比我预期的多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33191929/

相关文章:

c++ - 对于这种情况,什么是好的构建模式? (分区工具)

JAVA java.lang.reflect.Constructor 无法调用 Date 构造函数

c++ - hbrBackground 中的颜色窗口

c++ - Has-a关系的继承

PHP : What is the benefit of spl_autoload_register? 包含的性能

constructor - VB 中构造函数的正确语法?

c++ - 默认构造函数

c++ - 库适用于 Clang 但不适用于 GCC

c++ - 是否可以使用 decltype 来确定前向声明模板类的成员函数的返回类型?

c++ bash 添加到 PATH