c++ - vector <T *> 析构函数

标签 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));
    }
};

现在,构造函数工作正常。析构函数有一些问题。 目前,析构函数定义为:

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);
}

但每次调试时,它都会在以下位置中断:

void deallocate(pointer _Ptr, size_type)
    {    // deallocate object at _Ptr, ignore size
    ::operator delete(_Ptr);
    }

看起来我无法删除 this->children vector 中的指针,有什么方法可以成功解构类吗?

最佳答案

你的析构函数应该是:

A::~A(void)
{
    for (size_t i=0; i < children.size(); ++i)
        delete children[i];
}

您或许还应该研究一下复制构造函数。否则,这样的代码将失败:

{
    A foo;
    B bar = foo;
}

因为您将删除相同的指针两次。

这两篇文章中的一篇可能会帮助您理解:12

关于c++ - vector <T *> 析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10853076/

相关文章:

c++ - 清除 QML 图片缓存

php - PHP 上的矢量变量值

c++ - 如何避免在 C++ 中自动释放?

c++ - 使用指针作为容器迭代器是否违反标准

java - LibGdx 鼠标位置相对于正交相机而不是屏幕

c++ - Emacs:CEDET 安装:软件包 assoc 已过时

C++11 的 shared_ptr 赋值

c++ - 什么是更有效的堆栈内存或堆?

android - super 记录器 : not creating temp file or recording any audio

c++ - 取消分配类的实例是否也会取消分配由其对象/方法动态分配的任何内存?