Home >Backend Development >C++ >Why Do `constexpr` Vectors and Strings in C 20 Lead to Transient Allocation Errors?
constexpr C 20 Vectors and Strings: A Transient Allocation Dilemma
Despite the C 20 standard introducing constexpr support for vectors and strings, developers may encounter unexpected compiler errors when attempting to create constexpr objects of these types.
In the example below, the compiler raises an error indicating that the expression requires a constant value:
#include <vector> #include <string> int main() { constexpr std::string cs{ "hello" }; constexpr std::vector cv{ 1, 2, 3 }; return 0; }
Although Visual Studio 2019 version 16.11.4 claims to support constexpr vectors and strings, this issue stems from a limitation in C 20's constexpr allocation semantics.
Unlike constexpr variables, C 20 constexpr containers support only transient allocation. This means that the memory allocated during constant evaluation must be completely released before the end of evaluation. Vectors, however, inherently require dynamic memory allocation, which hinders their ability to meet this requirement.
As a result, this code is considered ill-formed as the vector allocation persists:
constexpr std::vector<int> v = {1, 2, 3};
However, transient allocation can still be utilized in constexpr contexts. Consider this example:
constexpr int f() { std::vector<int> v = {1, 2, 3}; return v.size(); } static_assert(f() == 3);
In this instance, the vector's memory allocation is transient because the memory is released when f() returns. Thus, it is permissible to use std::vectors during constexpr evaluations, provided that the allocation is transient.
The above is the detailed content of Why Do `constexpr` Vectors and Strings in C 20 Lead to Transient Allocation Errors?. For more information, please follow other related articles on the PHP Chinese website!