简体   繁体   English

为什么在 C++20 中将 std::vector::push_back 声明为 constexpr?

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

According to cppref , in C++20, std::vector::push_back is declared as follows:根据cppref ,在 C++20 中, std::vector::push_back声明如下:

constexpr void push_back(const T& value);

I cannot imagine a scenario in which push_back should be constexpr .我无法想象push_back应该是constexpr的场景。

What's the rationale behind?背后的原理是什么?

Is there any rationale behind?背后有什么道理吗?

This is the abstract of the proposal.这是提案的摘要。 There is no separate rationale section:没有单独的理由部分:

P1004R2 Making std::vector constexpr P1004R2 制作 std::vector constexpr

Abstract抽象的

std::vector is not currently constexpr friendly. std::vector 目前不是 constexpr 友好的。 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) .随着 [P0784R1] 和相关论文中对 constexpr 的要求放宽,我们现在可以制作 std::vector constexpr,为了支持 constexpr 反射工作(和其他明显的用例)我们应该这样做

In general all deterministic operations (so no rand() ) should be constexpr , because why not?一般来说,所有确定性操作(所以没有rand() )都应该是constexpr ,因为为什么不呢? 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.您可以为运行时和编译时计算使用相同的代码,这很好,因为您减少了重复并且您的 constexpr 代码更加惯用。 In case of the constexpr use case the memory allocation and push_back function are invoked in compiler virtual machine, which emulate your runtime machineconstexpr用例的情况下,内存分配和push_back函数在编译器虚拟机中调用,该虚拟机模拟您的运行时机器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM