Pseudo-destructor call does not destroy an object

前端 未结 1 1057
太阳男子
太阳男子 2020-11-28 13:19

Consider the following code:

#include 

typedef int t;
t a=42;

int main()
{
    a.t::~t();
    std::cout << a; //42
}
<
相关标签:
1条回答
  • 2020-11-28 13:29

    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, e.g. §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.

    0 讨论(0)
提交回复
热议问题