Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

C++20 Constexpr vector

The latest C++20 standard supports dynamic allocation memory in compile time with a limitation. The memory allocation cannot "go outside" the constant expression. That means that vector cannot be return and stored in a constexpr variable.

In the cppstories article there is the following example

#include <vector>
#include <string>
#include <algorithm>
constexpr std::vector<std::string> 
split(std::string_view strv, std::string_view delims = " ") {
 std::vector<std::string> output;
 size_t first = 0;
 while (first < strv.size()) {
 const auto second = strv.find_first_of(delims, first);
 if (first != second)
 output.emplace_back(strv.substr(first, second-first));
 if (second == std::string_view::npos)
 break;
 first = second + 1;
 }
 return output;
}
constexpr size_t numWords(std::string_view str) {
 const auto words = split(str);
 return words.size();
}
int main() {
 static_assert(numWords("hello world abc xyz") == 4);
}

This example compiles successfully. If I change

const auto words = split(str);

to

constexpr auto words = split(str);

I get following error

example.cpp (27): error C2131: expression did not evaluate to a constant (27): note: failure was caused by a read of a variable outside its lifetime (27): note: see usage of 'str' Compiler returned: 2

Based on the standard this expected since the compilers don’t support so-called "non-transient" memory allocations. But why no error is reported when const is used. In bot cases the code is executed in compile time

Answer*

Draft saved
Draft discarded
Cancel

lang-cpp

AltStyle によって変換されたページ (->オリジナル) /