Use const wherever possible in C++?

后端 未结 5 1344
死守一世寂寞
死守一世寂寞 2020-12-10 13:04

As stated in book Effective C++: \"Use const whenever possible.\", one would assume that this definition: Vec3f operator+(Vec3f &other); would be b

5条回答
  •  孤城傲影
    2020-12-10 13:21

    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).

提交回复
热议问题