Home >Backend Development >C++ >Why Are My C 20 `constexpr` `std::vector` and `std::string` Failing Compilation?

Why Are My C 20 `constexpr` `std::vector` and `std::string` Failing Compilation?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-01 20:05:14754browse

Why Are My C  20 `constexpr` `std::vector` and `std::string` Failing Compilation?

C 20 Constexpr Vector and String Not Working? A Tale of Transient Allocation

When attempting to create constexpr std::string and std::vector objects, you may encounter a puzzling compiler error. Despite using the latest supported Visual Studio version, the error message claims "the expression must have a constant value."

The Problem

The provided code utilizes:

constexpr std::string cs{ "hello" };
constexpr std::vector cv{ 1, 2, 3 };

However, the compiler complains, suggesting missing details.

The Solution

The issue stems from C 20's limited support for constexpr allocation. Specifically, transient allocation is required. This means that any memory allocated during constant evaluation must be deallocated before the evaluation completes.

Vectors, by nature of dynamic memory allocation, cannot be stored as constants because their memory persists after evaluation. Hence, the error about "points to memory which was heap allocated during constant evaluation."

Example of Transient Allocation

While vectors cannot be declared as constants, they can be used during constexpr functions with transient allocation:

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

static_assert(f() == 3);

In this code, the vector's memory is deallocated when f() returns, making the allocation transient and allowing it to be used in a constexpr function.

The above is the detailed content of Why Are My C 20 `constexpr` `std::vector` and `std::string` Failing Compilation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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