close
The Wayback Machine - https://web.archive.org/web/20220924160444/https://en.cppreference.com/w/Talk:cpp/language/destructor
Namespaces
Variants
Views
Actions

Talk:cpp/language/destructor

From cppreference.com

[edit] Specify how destructors can be explicitly called

E.g. calling destructors from within of destroyed class may be not obvious:

#include <iostream>
 
struct C
{
    C()
    {
        std::cout << this << " C()\n";
    }
 
    ~C()
    {
        std::cout << this << " ~C()\n";
    }
 
    // Assume author forgot to make it explicit. Now C() is convertible to int.
    /*explicit*/ operator bool()
    {
        std::cout << this << " operator bool()\n";
        return false;
    }
 
    void destroy_bad()
    {
        // Temporary instance of C is created, converted to bool, converted to
        // int, then int is bitwise inverted.
        ~C(); 
    }
 
    void destroy_good()
    {
        // Actual destructor call 
        this->~C(); 
    }
};
 
int main()
{
    char buffer[1024];
 
    C * c = new(buffer) C;
 
    c->destroy_bad();
    c->destroy_good();
}

Output:

0x7ffffbca59f0 C()
0x7ffffbca59bf C()
0x7ffffbca59bf operator bool()
0x7ffffbca59bf ~C()
0x7ffffbca59f0 ~C()

Rutsky (talk) 01:29, 18 December 2014 (PST)

it's an interesting (to a wannabe language lawyer like myself) corner case, perhaps we can work in an example similar to 3.8[basic.life]p7.4 along with a mention of the effect on lifetime (and with a link to lifetime), at which time it could be mentioned what happens if this-> is omitted. BTW, clang and gcc give helpful unused-value warnings on that ~C();. --Cubbi (talk) 08:04, 18 December 2014 (PST)