Using const
whereever possible is generally a good thing, but it's a bad wording. You should be using const
whereever it is possible and makes sense.
Above all else (it may, rarely, open extra optimization opportunities) it is a means to document your intention of not modifying something.
In the concrete example of a member operator+
that you have given, the best solution would not be to make everything const
, but a freestanding operator+
which bases on member operator+=
and takes one argument by value like so:
T operator+(T one, T const& two) const { return one += two; }
This solution works with T
appearing on either side of the plus sign, it allows for chaining, it doesn't replicate code, and it allows the compiler to perform the maximum of optimizations.
The semantics of operator+
require that a copy be made, so you can as well have the compiler make it (the other one will be optimized out).
It would be possible to make one
a const&
, but then you would have to manually make a copy, which would likely be sub-optimal (and much less intellegible).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…