delete'ing pointer of Type A pointing to pointer of type B
Suppose I have pointer of type ABC* and another pointer of type XYZ* and both derive from a common parent class.
If I assign XYZ* to ABC* by explicitly casting it, then what would happen if I call
delete abc; // abc is of type XYZ*
will I get any exception or will it work fine?
I have tried the above code and it doesn't crashes. So can anyone tell me in what cases will delete throw exception/fault/crash etc?
What are the cases in which delet'ing a pointer crashes the program? Will they crash if both of them have custom destructors defined
Edit: Here is my test code which works without any crashes
class ABC
{
public:
int a;
int b;
int c;
};
class XYZ
{
public:
double a;
double b;
double c;
};
开发者_如何学C
int main()
{
ABC* abc = new ABC();
XYZ* xyz = (XYZ*)abc;
delete xyz;
return 0;
}
P.S: I'm on Windows platform, if that helps.
EDIT2: Okay so after the readings, I change my question to, when will delete'ing a pointer cause a crash (not including the undefined behaviour)?
EDIT3: What will happen when delete is called? Whose destructor will be called?
If XYZ doesn't derive from ABC then you shouldn't be casting an object of the former to the latter - whether your delete works or not is immaterial.
It's illegal. If the type of the pointer to be deleted in a non-array delete expression differs from the dynamic type of the object being deleted then the type of the pointed to object must be a base class of the object being deleted and the base class must have a virtual destructor.
See ISO/IEC 14882:2003 5.3.5 [expr.delete]/2.
Your code will exhibit undefined behaviour. Note that this does not mean that it will crash, just that after you do a delete it will be in an undefined state. The idea that UB always leads to a crash (it would be nice if it did) is wrong.
If I assign XYZ* to ABC* by explicitly casting it
If XYZ is not a subclass of ABC then such an explicit cast, whether via reinterpret_cast
or a C-style cast, is undefined behavior. Sometimes you'll get lucky and the program will work right even though it has undefined behavior. Don't count your lucky stars, and don't ever intentionally invoke undefined behavior.
精彩评论