In C++, wherever I see in web an example of suffix increment operator declaration, it is always declared as
T& operator++(int);
and I believe this is the correct syntax of a suffix increment, isn’t it?
The issue is that, whenever I declare suffix increment, I declare return type with const keyword, so that it becomes lvalue-like.
Please see the example code:
class AClass
{
int foo;
public:
AClass(void) : foo(0) {};
// Suffix increment operator
// Consider adding const to return type
/* const */ AClass operator++(int)
{
AClass cp(*this);
foo++;
return cp;
};
// Prefix increment operator
AClass& operator++()
{
foo++;
return *this;
};
};
int main(int argc, const char* args[])
{
/* This code would fail to compile.
int bar = 5;
(bar++)++;
*/
// Similarily, I would expect this to fail
// but it will succeed unless I use const return type.
AClass a;
(a++)++;
}
I have never had problems about such a const-declared operator and I know it already saved our code from a bug made by a clumsy co-worker. So, my questions are:
- Are there any cons for such a practice? Is it a good practice indeed?
- What is the really correct declaration of suffix operator (I mean standards)?
- If this is not how the standard specifies but is already a good practice, shouldn’t it become a standard?
Thanks a lot for your answers!
Suffix increment returns a temporary, not a reference (this means your first signature is wrong):
Some people like to const-qualify the return value of the suffix operator to avoid writing stupid things like
which doesn’t modify
a(it appliesmodify_meto a temporary object). Contrast withwhich increments
aand then modifies it.Personally, I don’t think it is necessary (since you may be interested in the side effects of
modify_me). Moreover, in C++11, you may want to bind said temporary to a (non const) rvalue reference. Const qualifying the return type of suffix operators disables this possibility.