Dan*_*iel 2 c++ memory-management vector
我有一个类定义如下:
Class A
{
public:
int num;
A *parent;
vector<A *> children;
...
// constructor without parameters
A(void)
{
this->num = 3;
this->parent = 0;
for (int i=0;i<num;++i)
children.push_back(new A(this,num-1));
}
// constructor with parameters
A(A *a,int n)
{
this->num = n;
this->children->parent = a;
for (int i=0;i<num;++i)
this->children.push_back(new A(this,this->num-1));
}
};
Run Code Online (Sandbox Code Playgroud)
现在,构造函数工作正常.析构函数存在一些问题.目前,析构函数定义为:
A::~A(void)
{
if (this->parent!=0) this->parent = 0;
for (int i=0;i<(int)children.size();++i)
this->children[i]->~A();
vector <A *> ().swap(this->children);
}
Run Code Online (Sandbox Code Playgroud)
但是每当我调试它时,它都会破坏:
void deallocate(pointer _Ptr, size_type)
{ // deallocate object at _Ptr, ignore size
::operator delete(_Ptr);
}
Run Code Online (Sandbox Code Playgroud)
看起来我无法删除this-> children向量中的指针,有没有办法可以成功解构类?
你的析构函数应该是:
A::~A(void)
{
for (size_t i=0; i < children.size(); ++i)
delete children[i];
}
Run Code Online (Sandbox Code Playgroud)
您可能还应该查看复制构造函数.否则,这样的代码将失败:
{
A foo;
B bar = foo;
}
Run Code Online (Sandbox Code Playgroud)
因为你将两次删除相同的指针.
归档时间: |
|
查看次数: |
569 次 |
最近记录: |