我試圖弄清楚C++ 11規範中是否有任何東西。以下代碼預期的行爲(GitHub link here):C++評估順序
struct Scalar {
int data;
Scalar(int x) : data(x) {}
int get() {
return data;
}
Scalar &square() {
scale(data);
return *this;
}
void scale(int rhs) {
data *= rhs;
}
};
int main() {
Scalar v(3);
v.square().scale(v.get());
return v.data;
}
這主要是來自因爲發現這樣做g++
和clang++
之間不同的東西組成:
$ g++ --version
g++ (GCC) 6.2.1 20160830
Copyright (C) 2016 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ clang++ --version
clang version 3.9.0 (tags/RELEASE_390/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
$ g++ -std=c++11 order_of_ops.cpp -o a.out && ./a.out; echo $?
27
$ clang++ -std=c++11 order_of_ops.cpp -o a.out && ./a.out; echo $?
81
答案似乎應該是的第5.2.2節和第5.2.5節,但我無法追查具體的東西。
'方()'和'得到()'必須調用'規模之前調用()'。但是它們之間的相對順序並沒有被標準所指定。 – StoryTeller
我不會夢想嘗試這樣的事情。未定義的行爲。 –
當你想要的東西具體的呈現給您所TA'ing學生,這些都是你問(題型: – Pockets