使用 operator[] 插入时 std::map 大小不同(vc++ vs g++)
Different std::map size when inserting with operator[] (vc++ vs g++)
这个代码
#include <iostream>
#include <map>
int main()
{
std::map<int, std::size_t> m;
m[0] = m.size();
std::cout << m[0] << std::endl;
}
- 此代码有效吗?
- 如果是,哪个编译器是正确的?
- 直觉上我预计
1
。 vc++ 如何以 0
结尾?
Assignment operators - cppreference.com
When the left operand has reference type, the assignment operator modifies the referred-to object.
If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)
自 C++17 以来,order of evaluation 得到保证,m.size()
排在 m[0]
之前;结果保证为 0
.
- In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1
在 C++17 之前,行为是 unspecified。
顺便说一句,您可以使用 Gcc C++17 mode and Gcc C++14 mode.
观察不同的行为
这个代码
#include <iostream>
#include <map>
int main()
{
std::map<int, std::size_t> m;
m[0] = m.size();
std::cout << m[0] << std::endl;
}
- 此代码有效吗?
- 如果是,哪个编译器是正确的?
- 直觉上我预计
1
。 vc++ 如何以0
结尾?
Assignment operators - cppreference.com
When the left operand has reference type, the assignment operator modifies the referred-to object.
If the left and the right operands identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same)
自 C++17 以来,order of evaluation 得到保证,m.size()
排在 m[0]
之前;结果保证为 0
.
- In every simple assignment expression E1=E2 and every compound assignment expression E1@=E2, every value computation and side-effect of E2 is sequenced before every value computation and side effect of E1
在 C++17 之前,行为是 unspecified。
顺便说一句,您可以使用 Gcc C++17 mode and Gcc C++14 mode.
观察不同的行为