所以,我試圖想出一個在codegolf上用C++編寫When does x==x+2的解決方案,並提出這個片段只是爲了認識到我不知道它是如何工作的。我不確定爲什麼這兩個條件評估爲真。std ::向量運算符==:值或引用比較?
有沒有人知道標記爲line:
的行是真是因爲x == & x還是因爲x + 2是在==的左側之前求值?
#include <iostream>
#include <vector>
std::vector<int>& operator+ (std::vector<int> &v, int val)
{
v.push_back(val);
return v;
}
int main()
{
std::vector<int> x;
std::vector<int> y = x + 2; // y is a copy of x, and x is [2]
// how are both of these are true?
std::cout << (x==y) << "\n"; // value comparison [2]==[2]
line:
std::cout << (x==x+2) << "\n"; // reference comparison? &x == &(x+2)
// not sure if this is relevant
std::cout << (x+2==x) << "\n"; // also true
return 0;
}
看來 - 因爲矢量似乎是由值進行比較 - 如果x進行評價之前X + 2,則x將不等於x + 2(值)。我可能錯過了一些明顯的東西。提前致謝。
完全沒有。 gcc 4.5.3。 –
運算符'+'應該按值返回,不要改變輸入參數,像這樣:'std :: vector operator +(const std :: vector &v,int val);' –
ErikEsTT
我想知道標準是否允許'false '要回到這裏? – kennytm