1

我在当前的项目中遇到了困难。在以前的版本中,我使用了 std::vectors 一切都很好,没有内存泄漏,没有错误,很好。

然后我转而使用一些指针,因为它更优雅,而且我的性能有所提高。

所以我有像

class A
{
    private:
        std::string str;
    public:
        A() {str = "";}
};

class B
{
    private:
        std::string str;
        A* a;
    public:
        B() {str = ""; a = NULL; }
};

class C
{
    private:
        std::vector<B*> bs;
    public:
        C() { bs = std::vector<B*>(); }

};

我知道每次我使用new,我都必须delete在之后使用它。所以我为class Band创建析构函数class C

这就是我认为它应该看起来的样子:

B::~B()
{
    if ( this->a != NULL )
        delete this->a;
}

C::~C()
{
    while ( (this->bs).size() > 0 )
    {
        if ( (this->bs).back() != NULL )
            delete (this->bs).back();
        (this->bs).pop_back();
    }
    (this->bs).clear(); // not necessary since bs has size 0?
}

但是这样一来,我就会遇到各种错误,例如 valgrind 中的“无效读取大小为 4”。

我对析构函数应该是什么样子的想法好吗?我的代码还有什么问题?将私有std::string成员更改为std::string-pointers 会更好吗?str = "";在析构函数中这样做是必要的还是好事?

附带说明:请理解,我已经对“适当的析构函数”和类似的关键字进行了大量搜索,但没有帮助。如果你认为这个问题被问得太频繁了:我不知道,因为我不明白。

4

1 回答 1

1

Rob 所说的以及您的析构函数可以简化为:

B::~B()
{
    delete a;
}

C::~C()
{
    for (size_t i = 0; i < bs.size(); ++i)
        delete bs[i];
}
于 2012-05-11T14:26:37.140 回答