C++我应该在设置新对象时销毁对象中的旧对象吗?

Sta*_*art 1 c++

考虑以下类声明:

#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);
    }
};
Run Code Online (Sandbox Code Playgroud)

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

Luc*_*ore 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
};
Run Code Online (Sandbox Code Playgroud)

  • 编写`A():prop(NULL){}`而不是分配给`prop`可能略微更惯用 - 但这并不重要. (2认同)