使 ++o++ 抱怨具有用户定义的前置和后置增量运算符的类型
Make ++o++ complain for types with user defined pre- and postfix increment operators
我正在寻找一种方法来防止 ++x++
处理具有用户定义的前缀和后缀增量运算符的类型。
对于内置类型,后缀运算符的结果类型不是左值而是纯右值表达式,编译器会很好地抱怨。
我能想到的最简单的事情是 return 后缀增量运算符的 const:
struct S {
int i_;
S& operator++() {
++i_;
return *this;
}
S /*const*/ operator++(int) {
S result(*this);
++(*this);
return result;
}
};
int main() {
S s2{0};
++s2++;
}
这种方法有缺陷吗?
编辑:
多亏了回答,我找到了更多信息, here and of course on cppreference。
您可能需要 S& operator++() &
和 S operator++(int) &
。您在末尾缺少 &
,这使得运算符仅适用于左值。
您希望使前缀 ++
运算符仅对左值起作用。
此语法自 C++11 起有效。
S& operator++() & {
// ^ This & allows only lvalues for *this
++i_;
return *this;
}
我正在寻找一种方法来防止 ++x++
处理具有用户定义的前缀和后缀增量运算符的类型。
对于内置类型,后缀运算符的结果类型不是左值而是纯右值表达式,编译器会很好地抱怨。
我能想到的最简单的事情是 return 后缀增量运算符的 const:
struct S {
int i_;
S& operator++() {
++i_;
return *this;
}
S /*const*/ operator++(int) {
S result(*this);
++(*this);
return result;
}
};
int main() {
S s2{0};
++s2++;
}
这种方法有缺陷吗?
编辑:
多亏了回答,我找到了更多信息
您可能需要 S& operator++() &
和 S operator++(int) &
。您在末尾缺少 &
,这使得运算符仅适用于左值。
您希望使前缀 ++
运算符仅对左值起作用。
此语法自 C++11 起有效。
S& operator++() & {
// ^ This & allows only lvalues for *this
++i_;
return *this;
}