1

I have the following program that compiles with gcc and clang but doesn't compile with msvc c++20. Live demo

struct not_default_constructible { not_default_constructible() = delete; };
template<typename T> struct C
{
    static constexpr T t{};
};
template<class T>
struct myClass {
    C<T> new_t() { return {}; }
};

int main() {
    myClass<not_default_constructible> d;
    d.new_t();    
}

As we can see, the above program works with gcc and clang with both c++17 as well as c++20 but rejected by msvc with c++20 with the error:

<source>(6): error C2131: expression did not evaluate to a constant
<source>(6): note: failure was caused by call of undefined function or one not declared 'constexpr'
<source>(6): note: see usage of 'not_default_constructible::not_default_constructible'
<source>(15): note: see reference to class template instantiation 'C<T>' being compiled
        with
        [
            T=not_default_constructible
        ]

So I want to know which compiler is right here in C++20. I mean is the program well-formed in c++20.

Alan
  • 116
  • 9
  • Does this answer your question? [Initialisation of aggregate with default constructor deleted in c++20](https://stackoverflow.com/questions/57153739/initialisation-of-aggregate-with-default-constructor-deleted-in-c20) – BoP Nov 28 '22 at 08:52

1 Answers1

3

MSVC is wrong to complain. The definition of a static data member of a class template specialization is only supposed to be implicitly instantiated when the member is odr-used. But you are not odr-using C<not_default_constructible>::t anywhere.

If you actually do odr-use C<not_default_constructible>::t, then its definition will be implicitly instantiated and be ill-formed in C++20 because it will use the deleted default constructor.

In C++17 it will still be well-formed because not_default_constructible was still an aggregate class in C++17 (deleted constructors did not count against that property, but do since C++20) and so {} would be aggregate initialization which doesn't actually use the default constructor.

user17732522
  • 53,019
  • 2
  • 56
  • 105