我的情况是这样的:
class MyClass
{
private:
std::auto_ptr<MyOtherClass> obj;
public:
MyClass()
{
obj = auto_ptr<MyOtherClass>(new MyOtherClass());
}
void reassignMyOtherClass()
{
// ... do funny stuff
MyOtherClass new_other_class = new MyOtherClass();
// Here, I want to:
// 1) Delete the pointer object inside 'obj'
// 2) Re-assign the pointer object of 'obj' to 'new_other_class'
// so that 'obj' now manages 'new_other_class' instead of the
// object that just got deleted manually
}
};
有没有办法实现这个目标?以下代码是否符合我的要求?
void MyClass::reassignMyOtherClass()
{
// ... still, do more funny stuff (flashback humor :-)
MyOtherClass new_other_class = new MyOtherClass();
obj.reset(new_other_class);
}
new_other_class
的默认析构函数中是否取消分配MyClass
的内存?
答案 0 :(得分:4)
是的,它会。 你可以使用
obj.reset( new MyOtherClass() );
我最好使用这样的构造函数
MyClass():
obj( new MyOtherClass() )
{
}
答案 1 :(得分:1)