Why is std::vector::push_back declared as constexpr in C++20?

Viewed 312

According to cppref, in C++20, std::vector::push_back is declared as follows:

constexpr void push_back(const T& value);

I cannot imagine a scenario in which push_back should be constexpr.

What's the rationale behind?

2 Answers

Is there any rationale behind?

This is the abstract of the proposal. There is no separate rationale section:

P1004R2 Making std::vector constexpr

Abstract

std::vector is not currently constexpr friendly. With the loosening of requirements on constexpr in [P0784R1] and related papers, we can now make std::vector constexpr, and we should in order to support the constexpr reflection effort (and other evident use cases).

In general all deterministic operations (so no rand()) should be constexpr, because why not? You can use the same code for runtime as well as for compile time computation, which is great, because you reduce the repetition and your constexpr code is more idiomatic. In case of the constexpr use case the memory allocation and push_back function are invoked in compiler virtual machine, which emulate your runtime machine

Related