Use const wherever possible in C++?

2019-02-12 23:11发布

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!

4条回答
叛逆
2楼-- · 2019-02-12 23:16

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

查看更多
三岁会撩人
3楼-- · 2019-02-12 23:23

C++ FAQ:

If you find ordinary type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also.

You should use const when you want to be sure not to change variable accidentally or intentionally. Some constants (globals and class static, strings & integers, but not variables with nontrivial constructor) can be placed in read-only parts of the executable, therefore result in segmentation fault if you try to write to it.

You should be explicit using const as a specifier on functions that follow this principle as well as on function arguments. If you don't have to change actual argument, make it const. This doesn't limit the possible usages of such function, but extends them, because now they might be used on const arguments, and on const objects.

In declaration

const int* foo(const int* const&) const;

every const means something different and yes, obviously it should be used if it is needed.

Summary

Using const increases type-safety of your program.

C++ FAQ:

[18.3] Should I try to get things const correct "sooner" or "later"?

At the very, very, very beginning.

查看更多
爷、活的狠高调
4楼-- · 2019-02-12 23:39

When using const you are telling the compiler something.

It can then use that information to check that you are not doing something that you should not be doing and also enables it to optimize the code.

So when using const it enables it to be smarter.

查看更多
Anthone
5楼-- · 2019-02-12 23:41

I think that using const whenever possible is a good way to go. It adds implicit documentation to your code and increases type safety, as noted by the other answers.

It's nice to know that you can call const functions without having to worry about whether they change an object's internal state and that passing const pointers or references to something other object will keep it safe from encapsulation breakage. It also lets objects owning const references get the most value out of whatever that reference is pointing to.

Also, applying const from the get-go is a good idea because it can be a pain to add later. For example, if you have a class:

class A
{
public:

  //...

  int getCount()
  {
    return m_count;
  }

private:
  int m_count;
}

And another:

class B
{
public:

  //...

  int getInternalCount()
  {
    return m_a->getCount();
  }

private:
  A* m_a;
}

And you want to do:

void foo( const B* b )
{
  int count = b->getInternalCount();

  //-- Do something
}

This is a perfectly valid use case, but you then have to go and add const to multiple places to support it (B::getInternalCount() and A::getCount()). If you do it from the very start, it's actually quite easy to use const and it makes the design much more obvious to other developers. If you're working on your own, it still helps a lot, but it's not as much of a concern. When working in a team, though, I found it really helped when we started enforcing const and retrofitted some of our legacy code to adhere to it more.

Long story short: I recommend always using it.

查看更多
登录 后发表回答