Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

pointers - Use const wherever possible in C++?

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

Or an example with 5 const keywords: const int*const Foo(const int*const&)const;

Of course, you should only include const where there can be one. What Im asking is it a good practice to use them whenever possible? While it does give you more error safe code, it can get quite messy. Or should you, for example, ignore pointer and reference const (unless you really need it), and use it only on the types itself, as in const int* Foo(const int* parameter)const;, so it doesnt end up too messy?

Additional info: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...