What is the effect of call to a trivial destructor?

Viewed 257

Does a call to a trivial destructor end the lifetime of an object? I read this and this but didn't find a good explanation. These threads state that a trivial destructor call has no effect and code like struct A { int x; } a; a.~A(); a.~A(); is legal. But I found that example in the standard:

struct C { };
void f() {
    C * pc = new C;
    using C2 = C;
    pc->C::~C2(); // OK, destroys *pc
    C().C::~C(); // undefined behavior: temporary of type C destroyed twice
    using T = int;
    0 .T::~T(); // OK, no effect
    0.T::~T(); // error: 0.T is a user-defined-floating-point-literal (5.13.8)
}

Here C has trivial destructor but still double destruction of an object of type C has undefined behavior?

1 Answers

Starting with C++20 trivial destructor calls end the lifetime of objects. Before that they did not and it was valid to call the destructor multiple times.

In C++17 (draft N4659) trivial destructors are explicitly excluded from ending the lifetime in [basic.life]/1.3 and objects with trivial destructor would live instead until their storage duration ends or their storage is reused ([basic.life]/1.4).

This was changed with the resolution of CWG issue 2256 in this draft commit.

Also note that pseudo-destructor calls also end the lifetime in C++20, but did not before that. Both questions you link in your question are talking about such pseudo-destructor calls. See the compatibility note against C++17 in [diff.cpp17.basic]/1 of the draft (N4861).

Related