C ++ 17 make_optional constexpr-ness

This page says that the make_optional function in C ++ 17 returns constexpr optional<...> . I think that (maybe I'm wrong), this would require that optional<T> have a copy or move constexpr . However, this page also says that it is not.

I don’t know how make_optional can be implemented, since there is currently a C ++ 1z project. See this post for more details. Is there a workaround, or maybe it's just a standard project / cppreference error?

+7
c ++ std c ++ 17
source share
2 answers

Thanks to @Yakk and @TC for their explanation. I feel the example should make everything clearer:

 struct wrapper { int value; // non-explicit constexpr constructor constexpr wrapper(int v) noexcept : value(v) {} // non-constexpr copy & move constructors wrapper(const wrapper& that) noexcept : value(that.value) {} wrapper(wrapper&& that) noexcept : value(that.value) {} }; constexpr wrapper make_wrapper(int v) { return {v}; } int main() { constexpr auto x = make_wrapper(123); // error! copy/move construction, // but no constexpr copy/move ctor constexpr int y = make_wrapper(123).value; // ok static_assert(y == 123, ""); // passed } 

So, make_wrapper successfully returns a constexpr wrapper ; it is copying / moving (although this is usually eliminated by compilers), which prevents compilation of the code, since there is no constexpr copy / move constructor.

We can check the constexpr returned (temporary) wrapper object using its member value to initialize the constexpr variable.

+2
source share

You can directly build return values ​​in C ++ 11 with return {something}; If there are any implicit ctors that are constexpr , you can return them from the function.

+1
source share

All Articles