Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the defaulted constructor not constexpr here?

The following example seems to compile with Clang but not with gcc. Which one is right?

#include <type_traits>

template<typename T>
struct MyType
{
  constexpr MyType () = default;
  //constexpr MyType () {}

  constexpr bool is_int () const
  {
    return std::is_same_v<T, int>;
  }
};

constexpr auto foo ()
{
  MyType<int> retval;
  //MyType<int> retval {};

  return retval;
}

int main ()
{
  static_assert (foo ().is_int ());
}

Also, note that un-commenting any of the two commented lines (and removing the respective line above it) makes the program compile with gcc, too.

If gcc is right here, why doesn't it compile?

like image 677
Toby Brull Avatar asked Jan 01 '26 00:01

Toby Brull


1 Answers

The complaint is that you're using an uninitialized variable in a constexpr function. However - that's not the case, i.e. retval is default-initialized. So GCC is wrong, unless the standard has very weird language (which I doubt, but don't know for sure).

@StoryTeller suggests this is related to this bug report.

like image 135
einpoklum Avatar answered Jan 03 '26 14:01

einpoklum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!