Search code examples
c++language-lawyerexplicit-destructor-call

Various ways of calling C++ object destructor


A C++ object can be explicitly destructed using destructor call syntax (for non-class types pseudo-destructed). But it looks like that in addition to universally accepted syntax, almost any modern compiler supports its own ways of calling the destructor:

using T = int;
const int x = 1;
int main() { 
    x.~T();             //ok everywhere
    x.~int();           //#1: ok in MSVC only
    x.~auto();          //#2: ok in GCC only
    x.~decltype(x)();   //#3: ok in Clang and MSVC only
}

In addition to x.~T(), which works in all compilers, there are at least 3 other options, demo: https://gcc.godbolt.org/z/895bd9T5c

Are any of the options #1, #2 or #3 legal according to the standard or all of them are just extensions/bugs of the corresponding compilers?


Solution

  • The grammar doesn't allow (1) and (2), so those are illegal.
    (See [expr.prim.id.dtor] -> id-expression -> unqualified-id -> type-name.)

    The grammar does allow (3) though (... -> unqualified-id -> decltype-specifier), and I don't see anything in [expr.prim.id.dtor] that would disallow using decltype in this scenario.

    I tried several different things (making T a class type, making x dependent, etc), and in all cases GCC has rejected ~decltype(...). I'm assuming this is a GCC bug.