[英]Visual Studio C++ Compiler strange behavior, on Local variable objects
[英]Strange behavior in C++ compiler - Optimization?
我有一個函數,如果從地圖中刪除元素,則返回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
false | true
,應該是true | false
據我所知,這是true | false
。 然后我嘗試使用另一種方法打印它:
bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");
cout << boolalpha << b1 << " | " << b2 << endl;
這打印了預期的結果 - > true | false
true | false
。 我想這是編譯器優化代碼的一個技巧。 但猜測總是不對的嗎? (我使用的是g++ 4.8.5
編譯器)
誰能告訴我這里發生了什么?
函數調用期間的參數評估順序未指定。 這也適用於std::cout
,因為std::cout << a << b;
只是簡寫符號
operator<<(operator<<(std::cout, a), b);
評估順序在此處未指定 (參見評估順序 ),如函數調用(實際上是)
cout << boolalpha << students.remove("Sam") << " | " << students.remove("Sam") endl;
而在這里定義
bool b1 = students.remove("Sam");
bool b2 = students.remove("Sam");
cout << boolalpha << b1 << " | " << b2 << endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.