Is this there a defined behavior for this code that deletes a derived class through a base class pointer?
Does this code result in defined behavior?
class A {
int x;
};
class B {
short y;
};
class C {
double z;
};
class D : public A, public B, public C {
float bouncy;
};
void deleteB(B *b) {
delete b;
}
void is_it_defined() {
D *d = new D;
deleteB(d);
B *b =开发者_运维知识库 new D; // Is this any different?
delete b;
}
If it's not defined, why not? And if it is, what's it defined to do and why? Lastly, if it's implementation defined, could you give an example of what a common implementation might define the behavior to be?
Quoting Herb Sutter :
If deletion can be performed polymorphically through the base class interface, then it must behave virtually and must be virtual. Indeed, the language requires it - if you delete polymorphically without a virtual destructor, you summon the dreaded specter of "undefined behavior".
In your example, both delete
are performed through base class pointers and yield undefined behavior. Standard 5.3.5 (Delete) :
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
Here, both delete
act on static type B
while the operand's dynamic type is D
.
B
doesn't have a virtual destructor, it should have.
is it all concern about the virtual destructor? look at this:
class A
{
int x;
public:
virtual void fun()
{
return;
}
};
class D : public A
{
float bouncy;
};
void is_it_defined()
{
A *b = new D; // it`s ok!
delete b;
}
u see? it`s ok. The pointer b can be delete correctly. So, just need a vitual function to activate the polymorphic.
精彩评论