考虑以下类声明:
#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
?
答案 0 :(得分:5)
首先,您必须在构造函数中将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
};
答案 1 :(得分: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;
}
请参阅此处(特别是有关强异常保证的内容):
答案 2 :(得分:0)
如果构造函数始终分配新的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
。