【发布时间】:2015-08-11 04:49:20
【问题描述】:
我有点困惑如何在通过向量构造的对象上调用析构函数,但只有在我使用指针创建对象时调用一次。
#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 次析构函数调用。 2 次回击,我接到 5 次析构函数调用。 3 次推回,我接到 9 次析构函数调用。
通常如果我这样做,
Student * Univ = new Student("fn1", "ln1", 1);
delete Univ;
我只接到一个析构函数调用。
这是为什么?
【问题讨论】:
-
可能是向量空间不足,在别处获得了更多空间并将学生复制或移动到新空间。然后为旧空间中的学生调用析构函数。
-
@nwp 在一个较大的程序中,有大量的后退,这会是一个缺点吗?
-
这是无法避免的,除非你事先知道尺寸。但是调整大小很少发生,所以不要太担心。如果你能猜到大小,你可以使用vector.reserve(size)。列表没有这个问题,但它们还有其他更严重的问题。在 C++11 中,您可以通过移动语义大大减少开销。如果对象的复制/移动成本非常高,则可以使用指向对象的指针。这将最大限度地减少调整大小的成本,但会增加访问成本并使事情变得不那么方便。
标签: c++ vector destructor