Why is "delete * this" ever compiled?

I get 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 is compiling (using VC120 or Visual Studio 2013) and does not generate any warnings at all. Can anyone say why this is so?

Thanks.

+8
c ++ compilation mfc
source share
2 answers

This is an implicit conversion; the CWnd class has a conversion function operator HWND() , and HWND a pointer type.

Removing this HWND is a mistake, but the compiler does not know this and cannot warn you.

+8
source share

Why is "delete * this" ever compiled?

You can write a simple mcve that reproduces the behavior you are asking about:

 struct foo { operator int*() { return nullptr; } void bar() { delete *this; } }; int main() { foo f; f.bar(); } 

This compiles because foo implicitly converted to a pointer type. The same could be for your class.

+4
source share

All Articles