2016-12-07 62 views
3

我有一個函數返回true如果元素從地圖中刪除,或false否則。以下是我的函數的定義:C++編譯器中的奇怪行爲 - 優化?

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

誰能告訴我這裏發生了什麼?

+1

不同意這種重複的選擇確實存在,代碼不是未定義的行爲 –

回答

4

評價的順序是不確定這裏(CFR。order of evaluation)在函數調用只是速記符號(實際上是),而被定義

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

here

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

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