1

考虑以下类声明:

#include "classB.h"
class A {
private:
    B *prop;

public:
    A() { /* does stuff to set up B as a pointer to a new B */
    setB(const B& bar) { /* store a copy of B */
        // how do I manage the old *prop?
        *prop = new B(bar);
    }
};

应该setB()如何管理内存分配?我应该删除旧的*prop吗?如果是这样,我是否取消引用然后delete

4

3 回答 3

5

首先,您必须在构造函数中设置propNULL,否则如果您尝试这样做,您会得到未定义的行为delete

其次,您不取消引用,您只需分配指针。

第三,您应该删除析构函数中的内存,以免泄漏。

最后,如果你实现了析构函数,你还应该有一个复制构造函数和一个赋值运算符。

class A {
private:
    B *prop;

public:
    //set prop to NULL so you don't run into undefined behavior
    //otherwise, it's a dangling pointer
    A() { prop = NULL; }

    //when you set a new B, delete the old one
    setB(const B& bar) { 
        delete prop;
        prop = new B(bar);
    }

    //delete prop in destructor
    ~A() { delete prop; }

    //because you now have a destructor
    //implement the following to obey the rule of three
    A& operator = (const A& other);  //assignment operator
    A(const A& other);               //copy constructor
};
于 2012-04-27T23:37:15.840 回答
2

为了在分配抛出的情况下保持对象的状态,就像它在操作之前一样,你可能最好像这样实现它:

void setB(const B& bar)
{
    // Do this first, since it could throw.
    B *newProp = new B(bar);

    // Now delete the old one and replace it with the new one.
    delete prop;
    prop = newProp;
}

请参见此处(特别是关于强异常保证的部分):

http://en.wikipedia.org/wiki/Exception_guarantees

于 2012-04-27T23:54:53.317 回答
0

如果构造函数总是分配一个 new B,您可以将该空间重新用于其他B对象的副本。

A() { /* does stuff to set up prop as a pointer to a new B */
}

setB(const B& bar) { /* store a copy of B */
    *prop = bar;
}

并且不要忘记prop在析构函数中删除。

于 2012-04-27T23:44:52.370 回答