Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How will C++20 constexpr containers work?

As constexpr std::string and constexpr std::vector have been accepted into C++20, how will these be used? The linked papers are very short on details. Do we need to specify special constexpr allocators, making compile-time strings/vectors incompatible with their normal equivalents?

like image 710
Felix Dombek Avatar asked Jul 23 '19 11:07

Felix Dombek


People also ask

What is the point of constexpr?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

Is STD string a constexpr?

However, std::string objects generally cannot be constexpr, because any dynamically allocated storage must be released in the same evaluation of constant expression.

Can Unordered_map be constexpr?

Variable size container types, like std::vector or std::unordered_map , are generally useful for runtime programming, and therefore also potentially useful in constexpr computations. This has been made clear by some recent experiments such as the Constexpr ALL the things!

Is Vector a constexpr?

Formally, that's because vector constructor is not declared constexpr .


1 Answers

Those two papers depend heavily on P0784, which discusses how allocations at compile-time will work.

Incomplete answer:

  • Only std::allocator will work.
  • All allocations are tracked, and must be deallocated before compilation is complete. This means that you can do manipulations at compile-time, but you can't initialize string and vector variables to be used at run-time. (Personally, I think there's a good chance that this restriction will be lifted in a future version of the standard - but that's just my opinion.)
like image 60
Marshall Clow Avatar answered Oct 24 '22 01:10

Marshall Clow