Aussie AI
Overloaded Postfix Increment Operator
-
Book Excerpt from "Generative AI in C++"
-
by David Spuler, Ph.D.
Overloaded Postfix Increment Operator
The postfix increment operator (x++
) is a big slimy slug.
I'm not talking about your for
loop with “i++
” versus “++i
” for an integer, which is the same
on any compiler since about the 1990s,
despite the endless online arguments about it.
I'm talking about overloaded increment and decrement operators for classes.
In C++ you can declare separate prefix and postfix increment overloaded operators for a class,
by putting an extra dummy “int
” parameter in the postfix version.
You can also leave out a postfix version, and the prefix version will be called for both usages.
The default call to prefix versions is not a slug, but a potential bug if you copy-paste code or use postfix ++
in template code.
Also, returning the current object for the prefix increment operator is only a minor slug,
because you're returning a reference to the current object (and a reference is really just a pointer).
Postfix operations are much worse. They are slower than airport queues at Thanksgiving.
The semantics of the postfix increment operator (x++
) in the C++ language are effectively:
1. Create a temporary copy of your object.
2. Increment the current object.
3. Return the temporary object.
If you actually do this big shemozzle for a class object, you've got a whole lot of processing happening on a temporary object that's probably not even used. Maybe the optimizer will cut a lot of it as dead code, or maybe not. With the horrors of that echoing in your mind, here's my first suggestion:
Don't even declare postfix overloaded operators for your class.
Don't overload the postfix increment operator.
In fact, you can stop it being used by declaring a dummy version that is “private
” (stops external usage) with a “void
” function body
(stops internal usages).
private: void operator++(MyClass &x, int) void; // Postfix denied! void operator--(MyClass &x, int) void;
Void Return Type:
Note that attempts to call a postfix ++
operator on a class type may occur in
template instantiation with your type.
If it's your template, change the template code to use prefix operators.
If you really must define an overloaded postfix increment or decrement operator,
then here's my second suggestion:
Make the return type “void”
Hence, a basic usage of “x++
” will compile and work correctly.
Not only will it be efficient to not return anything,
but the compiler will also ensure that nothing more fancy will run.
A compilation error will block any use of postfix ++
that relies on the operator returning the old object.
In other words, this will be fine:
x++;
But this will get a compiler error alerting you to a problem:
y = x++; // Error
• Next: • Up: Table of Contents |
The new AI programming book by Aussie AI co-founders:
Get your copy from Amazon: Generative AI in C++ |