How is that possible that it is allowed to delete object with private destructor in the following code? I've reduced real program to the following sample, but it still compiles and works.
class SomeClass;
int main(int argc, char *argv[])
{
SomeClass* boo = 0; // in real program it will be valid pointer
delete boo; // how it can work?
return -1;
}
class SomeClass
{
private:
~SomeClass() {}; // ! private destructor !
};
You are trying to delete object of incomplete class type. C++ Standard says that you'll get undefined behavior in this case (5.3.5/5):
To detect such cases you could use
boost::checked_delete
:Because
SomeClass
type is not completely declared when invokingoperator delete
.Deleting such a pointer is undefined behavior, but in practice most compilers would just free the memory (if the pointer was non-NULL) and not call the destructor.
For example, g++ will give you a warning about this issue:
This code causes undefined behavior (UB). It is UB in C++ to
delete
an object of incomplete type having a non-trivial destructor. And in your code the typeSomeClass
is incomplete at the point ofdelete
, and it has a non-trivial destructor. Compilers usually issue a warning about this, since in C++ formally this is not a constraint violation.So, strictly speaking, your code doesn't "work". It simply compiles and does something undefined when run.
The compiler is just not required to catch this error. The reason for this is that this could be perfectly fine if your object has a trivial destructor. The compiler has no way of knowing what kind of destructor this type will eventually have, so it can't say for sure whether this is an error or not.