C++ 编译器中的奇怪行为 - 优化?

Strange behavior in C++ compiler - Optimization?

我有一个函数 returns true 如果从地图中删除元素,否则 false。以下是我的函数定义:

template <class Key, class Value>
bool HashMap<Key, Value>::remove(Key k)
{
  int result = map.erase(k);
  return (result == 1);
}

当我试图检查它是否工作时,我发现了非常奇怪的行为。

当我尝试使用以下语法打印结果时:

cout << boolalpha << students.remove("Sam") << " | " << students.remove("Sam") endl;

这打印了 false | true,据我所知应该是 true | false。然后我尝试使用另一种方法打印它:

bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");

cout << boolalpha << b1 << " | " << b2 << endl;

这打印了预期的结果 -> true | false。我想这是编译器为优化代码而做的一个技巧。但猜测并不总是正确的? (我正在使用 g++ 4.8.5 编译器)

谁能告诉我这里发生了什么?

未指定函数调用期间参数求值的顺序。 This applies to std::cout as well,因为 std::cout << a << b; 只是

的 shorthand 符号
operator<<(operator<<(std::cout, a), b);

这里的求值顺序是未指定(参见order of evaluation),就像在函数调用中(实际上是)

cout << boolalpha << students.remove("Sam") << " | " << students.remove("Sam") endl;

在这里定义

bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");

cout << boolalpha << b1 << " | " << b2 << endl;