[RESOLVED] Const correctness: const * const vs const &
I've never paid much attention to const correctness and have usually relied on my knowledge of the code to determine what I can and cannot modify. I feel this is a bad habit I need to get rid of. (for the sake of working with other programmers mainly) So I've started to change the current program I'm writing by applying const were needed.
However, my question is: Is there any difference between using a constant pointer to a constant variable (const * const) and a constant reference (const &)? To me it looks like they offer exactly the same limitation to the variable. What is considered good practise among C++ programmers? Or is it both okay as long as I am consistent?
Re: Const correctness: const * const vs const &
The rules I use are....
1) Never pass a non-primitive type by value unless I'm going to make a copy anyway. Always pass by reference; and if I don't intend to change the object, pass by const reference.
2) Pointers are used instead of references only when I'm specifying an array or a parameter which could be NULL.
Re: Const correctness: const * const vs const &
Quote:
However, my question is: Is there any difference between using a constant pointer to a constant variable (const * const) and a constant reference (const &)? To me it looks like they offer exactly the same limitation to the variable. What is considered good practise among C++ programmers? Or is it both okay as long as I am consistent?
The main difference is that the const-ness of the point can be cast away, so it *can* be modified. The reference can't be changed, period. I think I've also read that references can have a slight performance advantage because they don't have to be derefenced, but I can't really see that being anything remotely significant.
Pointers should pretty much be used only when you have to have them.
Re: Const correctness: const * const vs const &
Quote:
Originally Posted by
Speedo
The main difference is that the const-ness of the point can be cast away, so it *can* be modified.
Yeah but then whoever is writing that code also knows hes violating const.
Quote:
I think I've also read that references can have a slight performance advantage because they don't have to be derefenced, but I can't really see that being anything remotely significant.
Pointers should pretty much be used only when you have to have them.
Not sure if there is a performance difference since both pointers and references are memory adresses. But the point about only using pointers when needed is probably why most people recommend it. I think I'll just go with refs unless pointers are needed.