I am deriving a class from MFC CDialogEx
:
class MyDialog : public CDialogEx
{
public:
virtual void PostNcDestroy();
…
…
};
I implemented PostNcDestroy
as such:
void MyDialog::PostNcDestroy()
{
CDialogEx::PostNcDestroy();
delete *this; // oops, typo
}
I was surprised to see that this code compiles (using VC120, or Visual Studio 2013) , and generates no warning at all. Can anybody tell why this is the case?
Thank you.
When delete is used to deallocate memory for a C++ class object, the object's destructor is called before the object's memory is deallocated (if the object has a destructor). If the operand to the delete operator is a modifiable l-value, its value is undefined after the object is deleted.
delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.
delete keyword in C++ New operator is used for dynamic memory allocation which puts variables on heap memory. Which means Delete operator deallocates memory from heap. Pointer to object is not destroyed, value or memory block pointed by pointer is destroyed.
delete and free() in C++ In C++, the delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
It's an implicit conversion; the class CWnd
has an operator HWND()
conversion function, and HWND
is a pointer type.
Deleting that HWND
is an error, but the compiler doesn't know that and can't warn you.
Why does “delete *this” ever compile?
It's possible to write a simple mcve that reproduces the behaviour that you're asking about:
struct foo {
operator int*() {
return nullptr;
}
void bar() {
delete *this;
}
};
int main() {
foo f;
f.bar();
}
This compiles because foo
is implicitly convertible to a pointer type. Same could be the case for your class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With