使用operator[]插入时不同的std::map大小(vc++vsg++)

这段代码

#include <iostream>
#include <map>

int main()
{
    std::map<int, std::size_t> m;
    m[0] = m.size();
    std::cout << m[0] << std::endl;
}

将打印0用VC ++和1与G ++。

  • 这个代码有效吗?
  • 如果是,哪个编译器是正确的?
  • 直觉上我会期待1。vc++ 的结局如何0

回答

从 C++17 开始,求值的顺序是有保证的,m.size()排在前面m[0];结果保证是0

  1. 在每个简单赋值表达式 E1=E2 和每个复合赋值表达式 E1@=E2 中,E2 的每个值计算和副作用都在 E1 的每个值计算和副作用之前排序

在 C++17 之前,行为是unspecified。

顺便说一句,您可以使用Gcc C++17 mode和Gcc C++14 mode观察不同的行为。

  • Before C++17, the behavior is unspecified, but not undefined. `m[0]` and `m.size()` are both function calls. The execution of their bodies cannot overlap. This is the case even if their call sites are unsequenced.

以上是使用operator[]插入时不同的std::map大小(vc++vsg++)的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>