【发布时间】:2014-12-11 19:40:42
【问题描述】:
我创建的类的析构函数在作用域结束之前被调用。我认为当我向它添加另一个元素时,它与向量中的重新分配有关。我如何超越这个问题?我希望仅当对象到达我的代码中的范围末尾时才调用析构函数。
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
~A() { cout << "destructor called\n"; }
};
int main ()
{
A one, two;
vector<A> vec;
cout << "push_back one" << endl;
vec.push_back(one);
cout << "push_back two" << endl;
vec.push_back(two);
//destructor gets called here
system("pause");
return 0;
} //while i want it to be called here
【问题讨论】:
-
在向量上使用保留以防止重新分配。
-
您必须致电
reserve()。 -
我正在寻找不同的解决方法。调用 reserve() 对我来说听起来像是一个骗局。我想完全理解这个问题。也许通过添加一些代码让 A 类“更智能”?
-
与您的问题无关,但
using namespace std;和system("pause");是我最讨厌的两个问题。 -
如果向量的缓冲区空间不足,需要分配新的缓冲区,则必须销毁旧缓冲区的内容。没有办法解决这个问题。
标签: c++ class oop destructor