2つの同じ式が異なる結果をもたらす理由を混乱させましたか?唯一の違いは、式()でカスタムプリミティブラッパータイプを使用していることだけです。
わかりやすくするためにコードを提供しています。structInt{int value;
Int operator*(Int b) const{
return Int{value*b.value};
}
Int operator/(Int b) const{
return Int{value/b.value};
}
Int operator-(Int b) const{
return Int{value - b.value};
}
const Int& operator++() {
++value;
return *this;
}
Int operator--(int) {
Int copy{value};
value--;
return copy;
}
};
ostream& operator<<(ostream& out, Int x) {
out << x.value;
}
int main(){
int a = 11; Int A{11};
int b = 4; Int B{4};
cout << ++a / b * b-- - a << endl; // 0
cout << ++A / B * B-- - A << endl; // 4
}
また、Clangコンパイラは警告-Wunsequencedを表示しますが、プリミティブ型の式に対してのみです。
++a / b * b-- - a
変数はシーケンスポイントを挟まずに読み書きされるため、のようなすべての式の動作は未定義です。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加