skip to content

Since C++20, what may a C++ constexpr function do during constant evaluation that C++17 rejected, and what still fails?

level: middleimportance: should knowfreq 42%

answer

  1. heap memory that does not escape
  2. vector and string during evaluation
  3. virtual calls and try blocks
  4. the result must not own memory

basics

~20 s

C++20 lets constant evaluation allocate and free memory, so std::vector and std::string work inside it, call virtual functions, and contain try blocks. Still rejected: memory that outlives the evaluation, undefined behaviour, reinterpret_cast, non-constexpr calls and, until C++26, evaluating a throw.

solid answer

~40 s

C++20 made constant evaluation much closer to ordinary C++. A `constexpr` function may now use `new` and `delete`, and therefore `std::vector` and `std::string`, as long as everything allocated is freed before the evaluation ends (**transient allocation**). It may call virtual functions, contain `try` blocks, and leave a local uninitialized until it is assigned. C++23 added `static constexpr` locals and allows `goto` and non-literal variables in code that is not evaluated. Still not allowed: allocation that escapes into the result, so `constexpr std::vector<int> v = ...;` is an error; any undefined behaviour, which is diagnosed; `reinterpret_cast`; calls to non-`constexpr` functions; and, until C++26, evaluating a `throw`. The usual pattern is to build with a `std::vector` and copy into a `std::array` for the result.

code

cpp · 28 lines
cpp
#include <string>
#include <string_view>
#include <vector>

struct Field { virtual ~Field() = default; virtual int width() const = 0; };   // C++20: constexpr virtual
struct U16 : Field { constexpr int width() const override { return 2; } };
struct U32 : Field { constexpr int width() const override { return 4; } };

// Header layout "u16,u32,u32": the vector and the strings live only during evaluation.
constexpr int header_size(std::string_view layout) {
    std::vector<std::string> names;
    std::size_t start = 0;
    for (std::size_t i = 0; i <= layout.size(); ++i)
        if (i == layout.size() || layout[i] == ',') {
            names.emplace_back(layout.substr(start, i - start));
            start = i + 1;
        }
    int total = 0;
    for (const auto& n : names) {
        const Field* f = (n == "u16") ? static_cast<const Field*>(new U16) : new U32;
        total += f->width();   // virtual call during constant evaluation
        delete f;              // freed before evaluation ends
    }
    return total;
}

static_assert(header_size("u16,u32,u32") == 10);
int main() {}

go deeper

for a junior

Recall that C++20 constexpr functions can use std::vector and std::string internally, but a constexpr variable cannot be a vector.

for a middle

Explain transient allocation, list virtual calls and try blocks as C++20 additions, and show the copy-into-std::array pattern for results.

for a senior

Use constant evaluation as a built-in checker: core-language undefined behaviour is diagnosed there, and step limits warn when a computation belongs at run time.

for a principal

Weigh moving parsers and tables into constant evaluation: no startup cost and early errors, against build time and the minimum compiler the team must support.

## What changed in C++20 Before C++20, a `constexpr` function was limited to a fixed-size world: no heap, no virtual calls, no `try` blocks, and every local had to be initialized at its declaration. C++20 lifted most of that. During **constant evaluation** a function may now: - **allocate and free memory** with `new`/`delete` and `std::allocator<T>`, provided every allocation is deallocated within the same evaluation (the standard's wording for **transient allocation**); - therefore use **`std::vector` and `std::string`**, whose members became `constexpr` in C++20; - **call virtual functions**, and declare virtual functions `constexpr`; - contain **`try`/`catch` blocks**, although actually evaluating a `throw` is still not allowed until C++26; - use `dynamic_cast` and `typeid` on objects created in the evaluation; - declare a local without initializing it, as long as it is assigned before it is read; - change the active member of a union. The feature-test macro `__cpp_constexpr_dynamic_alloc` (`201907L`) marks transient allocation. ## A worked example: sizing a packet header while compiling A network stack describes headers as text, `"u16,u32,u32"`, and wants the size as a constant. The C++20 version splits the string into a `std::vector<std::string>`, creates a field object per name with `new`, asks it for its width through a virtual call, deletes it, and returns the sum. `static_assert(header_size("u16,u32,u32") == 10);` passes with `-std=c++20`; with `-std=c++17` Apple clang 21 rejects it with `virtual function cannot be constexpr` and `variable of non-literal type 'std::vector<std::string>' ... cannot be defined in a constexpr function before C++23`. ## Later additions | Standard | Added to constant evaluation | |---|---| | C++23 | `static` and `thread_local` variables in a constexpr function, if usable in constant expressions (`static constexpr char digits[] = "0123456789abcdef";`) | | C++23 | `goto`, labels and non-literal variables in the function body, as long as they are not evaluated | | C++26 | throwing and catching an exception, provided it does not escape the evaluation (`__cpp_constexpr_exceptions`, not yet in Apple clang 21) | | C++26 | placement `new` into storage created in the evaluation, and converting `void*` back to an object pointer | ## What still fails 1. **Escaping allocation.** The result of a constant expression may not hold memory allocated during it: ```cpp constexpr std::vector<int> ports() { return {80, 443, 8443}; } constexpr std::vector<int> kPorts = ports(); // error ``` Apple clang 21 reports `constexpr variable 'kPorts' must be initialized by a constant expression`, with the note `pointer to subobject of heap-allocated object is not a constant expression`. The fix is to use the vector **inside** the evaluation and return a fixed-size result: copy into a `std::array`, or compute only what is needed, as in `static_assert(ports().size() == 3)`, where the vector dies inside the assertion. A version that compiles keeps the vector inside the evaluation and returns a fixed-size copy: ```cpp constexpr auto kPorts = [] { std::array<int, 3> out{}; auto v = ports(); // allocated and freed in this evaluation for (std::size_t i = 0; i < out.size(); ++i) out[i] = v[i]; return out; }(); static_assert(kPorts[2] == 8443); ``` The immediately invoked lambda is itself evaluated while compiling, because it initializes a `constexpr` variable, and its `std::array` result holds no heap memory. 2. **Undefined behaviour.** Signed overflow, out-of-bounds access, a read of an uninitialized object, or a null dereference makes the expression non-constant, so it is a compile error wherever a constant is required. 3. **`reinterpret_cast`**, inline assembly that is evaluated, and calls to non-`constexpr` functions, including most of the C library. 4. **Evaluating a `throw`** before C++26, and an exception escaping the evaluation even in C++26. 5. **Implementation limits**, such as the number of evaluation steps or call depth; Clang and GCC have flags to raise them, but hitting one is a hint to rethink the design. ## How to answer Name the big three C++20 additions, **transient allocation, virtual calls and try blocks**, and give the rule that allocation must not escape, with the `std::array` workaround. Then add that core-language undefined behaviour is always diagnosed during constant evaluation, which is why moving a table or a parser to compile time also works as a test.

  • How do you get a compile-time table out of a computation that needs std::vector?
    Run the vector inside the evaluation and return a fixed-size copy. For example, an immediately invoked lambda initializes `constexpr auto kPorts = [] { std::array<int, 3> out{}; auto v = ports(); /* copy */ return out; }();`. The vector is allocated and freed inside the evaluation, and the `std::array` result holds no heap memory, so it is a valid constant.
  • Can a C++20 constexpr function contain a throw statement?
    Yes, it may contain one, and C++20 also allows `try` blocks. What is not allowed through C++23 is *evaluating* the `throw` during constant evaluation: a call that reaches it is not a constant expression. At run time the same function throws normally. C++26 lets constant evaluation throw and catch, as long as the exception does not escape.

  • constexpr functions still cannot use std::vector in C++20.
  • A constexpr std::vector variable keeps its elements in the binary since C++20.
  • Virtual functions can never be called during constant evaluation.
  • Signed overflow during constant evaluation wraps like at run time.
  • C++20 lets constant evaluation throw and catch exceptions.

Assumes C++20 for transient allocation, virtual calls and try blocks, C++23 for static constexpr locals, and names C++26's constexpr exceptions as a draft feature Apple clang 21 lacks.