c++ - 使用 Vectors 创建对象时如何调用析构函数

标签 c++ vector destructor

对于如何在通过 vector 构造的对象上调用析构函数,我有点困惑,但是当我使用指针创建对象时只有一次。

#include <iostream>
#include <vector>
#include <string>

class Student
{
    std::string first;
    std::string last;
    int age;

public:
    Student();
    Student(std::string f, std::string l, int a) : first(f), last(l), age(a)
    {
    };
    ~Student()
    {
        cout << "Destructor\n";
    }
};

int main()
{
    std::vector<Student> Univ;
    Univ.push_back(Student("fn1", "ln1", 1));
    Univ.push_back(Student("fn2", "ln2", 2));
    Univ.push_back(Student("fn3", "ln3", 3));
    return 0;
}

当我推回一次时,我收到了两次对析构函数的调用。 2 次后退,我收到 5 次析构函数调用。 3 次推回,我收到 9 次析构函数调用。

通常如果我这样做,

Student * Univ = new Student("fn1", "ln1", 1);
delete Univ;

我只接到一次析构函数调用。

这是为什么?

最佳答案

您正在创建一个临时的 Student,您将其传递给 push_back,后者将其复制到 vector 中。结果是您使用了每个 Student 实例的两个拷贝,并且调用了每个实例的析构函数。此外,当您添加更多 Student 并且 vector 调整大小时,现有内容将被复制到新分配的内存中,从而导致更多的析构函数调用。

如果您有可用的 C++11 功能,您可能需要查看 move semantics .

关于c++ - 使用 Vectors 创建对象时如何调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30510618/

相关文章:

c++ - 插入具有没有复制构造函数的对象的 vector

c++ - 在 vector 声明中移动 unique_ptr

c++ - 继承和析构函数 - 理论问题 - C++

c++ - Cuda - 体系结构 x86_64 OS X 的 undefined symbol

c++ - 安装使用 Bazel 构建的库

c++ - Vector size() 被 NetBeans 标记为错误 : Unable to resolve Identifier

c++ - boost::function 变量在析构函数中为空

c++ - 在类型化的 std::array 中放置 new 和 std::destroy_at 的安全性?

c++ - PlaySound 无法播放两个异步声音

c++ - 在 C++ 中使用泰勒级数求数字的自然对数