Home > Mobile >  Prospective destructors in C
Prospective destructors in C

Time:05-18

I have this code and this outputs the following:

link to the following example https://godbolt.org/z/z8Pn9GsTv

template <typename T>
struct A1 {
    A1() {
        std::cout << "construction of a1" << std::endl;
    }

    ~A1() {
        std::cout << "destruction of a1" << std::endl;
    }
    ~A1() requires (std::is_same_v<T,int>) {
        std::cout << "it is an int" << std::endl;
    }
};

int main() {
    A1 <int>a;
    
    return 0;
}

output:

construction of a1
destruction of a1

but swapping places of destructors it gives other result:

link to the code https://godbolt.org/z/vxj7dPqaj

template <typename T>
struct A1 {
    A1() {
        std::cout << "construction of a1" << std::endl;
    }

    ~A1() requires (std::is_same_v<T,int>) {
        std::cout << "it is an int" << std::endl;
    }
    ~A1() {
        std::cout << "destruction of a1" << std::endl;
    }
};

output:

construction of a1
it is an int

wondering is this a bug?

CodePudding user response:

That's indeed a reported Clang bug1, as noted by Quimby.

Note that the second snippet (the one with the the constrained destructor first) doesn't really "work" in Clang, which just ignores the second destructor2.

Also note that, unlike gcc, at the moment I'm writing, Clang doesn't seem to have implemented [P0848R3] (which is about conditional trivial special member functions) yet3.


1) https://bugs.llvm.org/show_bug.cgi?id=50570
2) See e.g.: https://godbolt.org/z/rff7qfK65
3) See the reported values of the feature test macro __cpp_concepts, e.g. here: https://godbolt.org/z/P4z3Pj5vT

CodePudding user response:

In your 2'nd code,

Try changing this:

A1 <int>a;

To this:

A1 <double>a;

And you'll get the output:

construction of a1
destruction of a1 // With MSVC & GCC compiler

My interpretation here is that when the condition for the first constructor (with requires) fails, the 2'nd constructor is called which prints "destruction of a1" and destroys a.

Here is a more detailed explanation...

CodePudding user response:

On your class template, you have two destructors definition recipe. During instantiation the The compiler gets the "first" recipe that match the signature needed. Depending the compiler depending the result. I think clang, gcc and mingw will provide the same result, msvc approach is different. https://cplusplus.github.io/CWG/issues/1495.html

  • Related