Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12201

Multiple calls to the delete when destructors throw exceptions

$
0
0

The code above works if compiled with Visual Studio. If the destructor throws an exception the operator delete is not called. If the destructor doesn't throw an exception the operator delete is called. But the same code causes Segmentation fault if compiled with gcc on Linux. It doesn't work even if there is no std::string member in the class. It terminates with "free(): double free detected in tcache 2". This means that the operator delete is called even if the destructor throws an exception. Is the behavior undefined according to the C++ standard? If so, does it mean that delete cannot be called again if the first call threw an exception?

#include <string>#include <iostream>class MyClass{public:    void *operator new(size_t size)    {        void *p = std::malloc(size);        if (!p) throw std::bad_alloc();        return p;    }    void operator delete(void *p)    {        std::free(p);    }    ~MyClass() noexcept (false)    {        if (s == "123") throw int{};    }    std::string s{"123"};};int main(){    MyClass* myobject = new MyClass{};    try    {        delete myobject;    }    catch (...) {}    std::cout << "<" << myobject->s << ">";    myobject->s = "abc";    delete myobject;    return 0;}

I compiled and ran the code on both Windows using Visual Studio and Linux using GCC. I expected it to work on both platforms, but it didn't work on Linux with GCC


Viewing all articles
Browse latest Browse all 12201

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>