简体   繁体   中英

Pseudo-destructor call does not destroy an object

Consider the following code:

#include <iostream>

typedef int t;
t a=42;

int main()
{
    a.t::~t();
    std::cout << a; //42
}

I'm expected that a will be destroyed. But it is not true, why? How does do that pseudo-destructor call will be destroyed the object?

But it is not true, why?

§5.2.4/1:

The only effect is the evaluation of the postfix-expression before the dot or arrow.

Where the postfix-expression is the expression of the object for which the call takes place. Thus a pseudo destructor call, as a call to a trivial destructor, does not end the lifetime of the object it is applied to. For instance,

int i = 0;
(i += 5).~decltype(i)();
std::cout << i;

You can't actually call a destructor for scalars, because they don't have one (see [class.dtor]). The statement is solely allowed for template code in which you call the destructor of an object whose type you don't know - it removes the necessity of writing a specialization for scalar types.


It was noted in the comments that [expr.pseudo] does imply the existence of a destructor for scalars by

The use of a pseudo-destructor-name after a dot . or arrow -> operator represents the destructor for the non-class type named by type-name .

However, this is inconsistent with other parts of the standard, eg §12, which calls a destructor a special member function and mentions that

A destructor is used to destroy objects of its class type.

It appears to be an imprecision created in C++98 days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM