Home > Backend Development > C++ > Why Do I Get Compiler Errors When Using `constexpr std::vector` and `constexpr std::string` in C 20?

Why Do I Get Compiler Errors When Using `constexpr std::vector` and `constexpr std::string` in C 20?

Barbara Streisand
Release: 2024-12-01 11:48:10
Original
481 people have browsed it

Why Do I Get Compiler Errors When Using `constexpr std::vector` and `constexpr std::string` in C  20?

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 };
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template