Home > Backend Development > C++ > Why Aren't My C 20 `constexpr` `std::vector` and `std::string` Working?

Why Aren't My C 20 `constexpr` `std::vector` and `std::string` Working?

Mary-Kate Olsen
Release: 2024-12-06 10:42:13
Original
532 people have browsed it

Why Aren't My C  20 `constexpr` `std::vector` and `std::string` Working?

C 20 constexpr Vector and String Not Working

In this issue, a programmer attempts to create constexpr objects of std::string and std::vector, but encounters a compiler error stating that the expression must have a constant value. The issue arises despite using the latest Microsoft Visual Studio 2019 version, which supports constexpr strings and vectors.

Problem Explanation

The error stems from the limited constexpr allocation support in C 20, which only allows for transient allocation. Transient allocation requires the allocated memory to be completely deallocated by the end of constant evaluation.

Example of Invalid Code

The following example illustrates the error:

int main() {
    constexpr std::vector<int> v = {1, 2, 3};
}
Copy after login

Here, the allocation for v persists, making it non-transient. The compiler correctly produces an error indicating that the expression did not evaluate to a constant because v holds onto a heap allocation during constant evaluation.

Example of Valid Code

However, using std::vector during constexpr time is possible with transient allocation.

constexpr int f() {
    std::vector<int> v = {1, 2, 3};
    return v.size();
}

static_assert(f() == 3);
Copy after login

In this example, v's allocation is transient since the memory is deallocated when f() returns. This allows for the use of std::vector during constexpr time.

The above is the detailed content of Why Aren't My C 20 `constexpr` `std::vector` and `std::string` Working?. 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