考虑以下类声明:
#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吗?
首先,你必须设置prop到NULL在构造函数中,否则你会得到未定义的行为,如果你尝试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)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |