6

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?

cigien
  • 57,834
  • 11
  • 73
  • 112
xmllmx
  • 39,765
  • 26
  • 162
  • 323
  • 8
    Maybe has to do with making the `constexpr std::vector` as a whole(?). Check this [thread](https://stackoverflow.com/a/52801072/14624729). – rawrex Jun 23 '21 at 06:10
  • Any inconvenience if `resize` is not `constexpr`? – xmllmx Jun 23 '21 at 06:14
  • 1
    You wouldn't be able to use resize in a constant context. – eerorika Jun 23 '21 at 06:14
  • 1
    Can `resize`, or even `push_back`, be used in a constant context? @eerorika – xmllmx Jun 23 '21 at 06:17
  • 2
    @xmllmx In C++20, yes: https://godbolt.org/z/KKb8dPo44 (only MSVC seems to have implemented constexpr vector so far). – eerorika Jun 23 '21 at 06:31
  • 1
    Mutable functions has been done `constexpr` to allow their usage in constexpr functions. C++20 now allows `std::vector` usage in constexpr functions. – Jarod42 Jun 23 '21 at 07:53

2 Answers2

4

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).

eerorika
  • 232,697
  • 12
  • 197
  • 326
3

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

slsy
  • 1,257
  • 8
  • 21