Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does “delete *this” ever compile?

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.

like image 929
Benoit Avatar asked Apr 18 '16 11:04

Benoit


People also ask

What does C++ delete actually?

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.

What is difference between delete and delete [] in C++?

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.

Does Delete Delete a pointer?

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.

How do you delete a pointer in C++?

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.


2 Answers

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.

like image 70
molbdnilo Avatar answered Oct 04 '22 05:10

molbdnilo


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.

like image 44
eerorika Avatar answered Oct 04 '22 05:10

eerorika