Constexpr Vectors and Strings in C 20: Resolving Compiler Errors
When attempting to create constexpr std::string and std::vector objects, you may encounter a compiler error indicating that the expression lacks a constant value. Despite using the latest Microsoft Visual Studio 2019 version, which supports constexpr strings and vectors, this error can persist.
Transient Allocation vs. Non-Transient Allocation
The issue arises from the fact that constexpr allocation support in C 20 is limited to transient allocations. Transient allocations are deallocated by the end of constant evaluation, preventing the persistence of the allocation.
In your case, the use of std::vector and std::string involves dynamic memory allocation, which is non-transient. Therefore, the compiler flags this as a violation of the transient allocation restriction.
constexpr std::vector cv{ 1, 2, 3 };
Solution for Transient Allocation within Constexpr
To resolve this issue and use vectors or strings within constexpr, ensure that the allocation is transient. This means that the memory allocation must be completely deallocated before constant evaluation ends.
For instance, you can use a function to perform the allocation within constexpr, as in the following example:
constexpr int f() { std::vector<int> v = {1, 2, 3}; return v.size(); } static_assert(f() == 3);
In this case, the vector's allocation is transient because the memory is deallocated when the function returns. This allows for the use of std::vector during constexpr time.
The above is the detailed content of Why Do I Get Compiler Errors When Using `constexpr std::vector` and `constexpr std::string` in C 20?. For more information, please follow other related articles on the PHP Chinese website!