Previous section   Next section

Imperfect C++ Practical Solutions for Real-Life Programming
By Matthew Wilson
Table of Contents
Chapter 28.  Increment Operators


28.1. Missing Postfix Operators

Since C++ lets you take responsibility for things—in contrast to some of the annoyingly nannying more "modern" languages—you are allowed to define prefix methods without the postfix equivalents, and vice versa. The problem in this case is that compilers exhibit different behavior when an operator is missing. For example, if your class defines only the preincrement operator, and your client code places an instance of your class in a postfix increment expression, some compilers will issue an error, whereas others will only issue a warning. Table 28.1 summarizes the behavior for a range of compilers.

In my opinion, such a thing is unambiguously an error, and I cannot conceive of a reason such behavior would be implemented, unless it is to pander to sloppy application programmers who are too unprofessional to use the appropriate form. In the other direction—that is, substituting a prefix call with a postfix operator—all the compilers do the right thing and reject it outright. If anything, this adds weight to my supposition.

Clearly, there's danger here. The semantics of the two operators are significantly different. If your compiler substitutes one for the other, your program is incorrect. Thankfully the majority of compilers will reject outright the substitutions and those that allow it still issue a warning, but if you're working with one of the warning-only compilers and your coworkers have messed with the warning levels,[1] it's possible that it could slip through.

[1] I suggest your co-worker, since I know you'd never do such a thing.

Table 28.1.

Compiler

Behavior

Borland

Warning, and uses prefix operator

CodePlay

Error

CodeWarrior

Error

Comeau

Error

Digital Mars

Warning, and uses prefix operator

GCC

Error

Intel

Warning, and uses prefix operator

Visual C++

Warning, and uses prefix operator

Visual C++ (-Za)

Error

Watcom

Error


Imperfection: Some C++ compilers will substitute prefix increment/decrement overloaded operators at the call site in place of absent postfix equivalents.


The solution here is pretty simple. You just declare the overload that you do not wish to use with private access. No compilers will substitute the publicly accessible prefix in place of a private postfix operator and vice versa.

This is actually the better solution anyway, since it's an overt expression of your design intentions; there's very little chance a maintenance programmer will mistake your intention if it's private and festooned with a comment mentioning its intended inaccessibility.


      Previous section   Next section