I'm looking for a way to prevent ++x++
from working for types with user defined prefix and postfix increment operators.
For builtin types the result type of the postfix operator is not an lvalue but a prvalue expression and the compilers complain nicely.
The simplest thing i can think of is to return const for the postfix increment operator:
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++;
}
Is this approach flawed?
Edit:
Thanks to the answers, i found more information here , here and of course on cppreference .
You probably want S& operator++() &
and S operator++(int) &
. You're missing the &
at the end that makes the operators only work on lvalues.
You are looking to make the prefix ++
operator work only on lvalues.
This syntax works since C++11.
S& operator++() & {
// ^ This & allows only lvalues for *this
++i_;
return *this;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.