为什么 std::vector::push_back 在 C++20 中声明为 constexpr?
Why is std::vector::push_back declared as constexpr in C++20?
根据cppref,在C++20中,std::vector::push_back
声明如下:
constexpr void push_back(const T& value);
我无法想象 push_back
应该是 constexpr
的场景。
背后的原理是什么?
Is there any rationale behind?
这是提案的摘要。没有单独的基本原理部分:
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).
一般来说,所有确定性操作(所以没有 rand()
)都应该是 constexpr
,为什么不呢?您可以对运行时和编译时计算使用相同的代码,这很好,因为您减少了重复,并且您的 constexpr 代码更加地道。在 constexpr
用例的情况下,内存分配和 push_back
函数在编译器虚拟机中调用,它模拟您的运行时机器
根据cppref,在C++20中,std::vector::push_back
声明如下:
constexpr void push_back(const T& value);
我无法想象 push_back
应该是 constexpr
的场景。
背后的原理是什么?
Is there any rationale behind?
这是提案的摘要。没有单独的基本原理部分:
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).
一般来说,所有确定性操作(所以没有 rand()
)都应该是 constexpr
,为什么不呢?您可以对运行时和编译时计算使用相同的代码,这很好,因为您减少了重复,并且您的 constexpr 代码更加地道。在 constexpr
用例的情况下,内存分配和 push_back
函数在编译器虚拟机中调用,它模拟您的运行时机器