Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ destructor calls a delete operator?

Why does my MSVC12 compiler not like this?

#include <new>

class thing
{
public:
    thing() {}
    ~thing() {}
    static void operator delete(void* ptr) = delete;
};

int main()
{
    int g;
    void* p = &g;
    thing* t1 = new(p) thing();
    t1->~thing();

    return 0;
}

The error I get is oddly on the closing brace of main():

Error 2 error C2280: 'void thing::operator delete(void *)' : attempting to reference a deleted function

If I comment out the explicit destructor call, the error goes away, implying that the explicit destructor call is trying to call operator delete(void*). This does not make intuitive sense. As you can probably see from the code here, I've already managed my own memory, and I don't want anyone to call delete on thing ever.

like image 264
Kumputer Avatar asked Mar 23 '16 23:03

Kumputer


People also ask

Is destructor called with delete?

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 does a destructor delete?

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

What is the difference between destructor and delete operator?

So delete is for managing the dynamic memory, but the destructor is a method of the class itself, which is always called when the object is getting freed from the memory (stack or heap).

Is delete called automatically in C++?

When an object goes out of scope normally, or a dynamically allocated object is explicitly deleted using the delete keyword, the class destructor is automatically called (if it exists) to do any necessary clean up before the object is removed from memory.


2 Answers

This is definitely a bug since by simply replacing the virtual call to the destructor with a nonvirtual one: t1->thing::~thing() it works. But obviously in this case there is no inheritance involved and therefore no difference between the two forms.

You can try and submit the bug through the Microsoft Connect site for VS

like image 55
Zak Goichman Avatar answered Oct 07 '22 18:10

Zak Goichman


The consensus in this thread is that this is a compiler bug unique to MSVC++. I have reported this to Microsoft here:

https://connect.microsoft.com/VisualStudio/Feedback/Details/2511044

UPDATE: MS reports that the issue is resolved and will be available in the next VS update.

like image 34
Kumputer Avatar answered Oct 07 '22 19:10

Kumputer