Jump to content

  • Log In with Google      Sign In   
  • Create Account

#ActualRavyne

Posted 05 February 2013 - 05:32 PM

You only need a const qualifier if you're passing by reference/pointer and you don't want the function to change the object being passed.


In addition to documenting your intent, const does have a function in this case -- it prevents you from modifying the argument inside the function body. I know it might seem useless to enforce rules on yourself, but this kind of defensive coding helps you to not make trivial mistakes, and prevent future code maintainers from violating your assumptions -- e.g. if your implementation assumes the argument to be constant, but you don't mark it as such, and someone comes along later to fix a bug and modifies it.

I would, and in fact do, go so far as to pass all arguments as const by default, regardless of whether they are by value or by reference. In most cases I would even go one further and take a local copy of that const parameter (in the smallest possible scope) if I wanted to modify it. One place I *don't* do this is when I mean to enable the RVO (the Return Value Optimization), as I do when implementing operator+ in terms of operator+= in my classes.

#1Ravyne

Posted 05 February 2013 - 05:30 PM

You only need a const qualifier if you're passing by reference/pointer and you don't want the function to change the object being passed.

 

In addition to documenting your intent, const does have a function in this case -- it prevents you from modifying the argument inside the function body. I know it might seem useless to enforce rules on yourself, but this kind of defensive coding helps you to not make trivial mistakes, and in some cases prevent future code maintainers from violating your assumptions -- e.g. if your implementation assumes the function to be constant, but you don't make the parameter constant, and someone comes along later and modifies it.

 

I would, and in fact do, go so far as to pass all arguments as const by default, regardless of whether they are by value or by reference. In most cases I would even go one further and take a local copy of that const parameter (in the smallest possible scope) if I wanted to modify it. One place I *don't* do this is when I mean to enable the RVO (the Return Value Optimization), as I do when implementing operator+ in terms of operator+= in my classes.


PARTNERS