Is it okay for an object to tell its owner to delete it
I have a scenario that is somewhat like this:
class Owner {
public:
enum Type {TypeB, Type开发者_C百科C};
void swap(Type type);
private:
A* m_a;
};
class A {
};
class B : public A {
void foo();
Owner* m_owner;
};
class C : public A {
void bar();
Owner* m_owner;
};
void Owner::swap(Type type) {
if (type == TypeC) {
delete m_a;
m_a = new C();
} else if (type == TypeB) {
delete m_a;
m_a = new B();
}
}
void B::foo() {
m_owner->swap(TypeC);
// will be deleted after this!!
}
There's an owner class that has a pointer to a base type A. That object of type B has a back pointer to its owner. There is a scenario where we'd want that object to tell its owner to swap it for another A type: C.
Is it safe from B::foo to tell its owner to delete it? I know if you do anything after the call to Owner::swap() it will crash. It is kind of like a "delete this" scenario.
If you've defined A
's destructor as virtual
then that is perfectly okay.
By the way, your code needs small correction:
else if (type == TypeB) {
delete m_a; //not m_b, as Owner doesn't have any member named `m_b`.
m_a = new B();
}
But I'm wondering which object gets deleted here, the one which calls swap
function? If so, then I would say there is a design problem with your classes, and your program may crash thereafter.
It ok to say the object owner to delete the object as long as you don't use it anymore. It also ok for an object to commit suicide (delete this
), the Standard doesn't make any moral judgments in this case.
It will crash (not surely crash, but it will start a memory corruption scenario) if after calling swap you try to access a field in the class.
All I'm saying is:
void B::foo() {
//this valid
m_owner->swap(TypeC);
//this invalid
}
精彩评论