I'm trying to understand const-correctness with references, I think I understand it with pointers but references confuse me.
Please correct me if I'm wrong:
When we declare a int * IntPointer; we have a pointer which can do pretty much anything, it can point to different variables and change their values (providing that those same variables aren't const);
When we declare constint * IntPointer; we have a pointer to a const int which means we can't change the value of the variable to which it is pointing but we can change the pointer to point to other variables.
When we declare a constint * const IntPointer; we have a pointer which can't be reassigned, nor can it change the value of it's variable.
With references are all of these situations possible? void f(const A & a)
this void f(A const & a) EDIT: My bad void f(A & const a)
and this: void f(const A const & a) EDIT: My bad void f(const A & const a)
I understand the first one and I use it quite often because I know that "a" acts as an alias to a const value but I don't get the other two, could you please try to explain how they work and what they are used for?
Having the const after the & is kindof pointless, albeit legal. It just means you can't rebind the reference to another variable, which is already the behaviour of references. You tend to only use that const with pointers (can't change what the pointer points to)
EDIT: nevermind it's not legal, see my post below.
Those are the same, but it's not the same meaning for Pointers and References.
OP has them right for pointers, and g++ doesn't even let you do int& const foo = bar; anymore:
wrong.cpp: In function ‘int main()’:
wrong.cpp:5: error: ‘const’ qualifiers cannot be applied to ‘int&’
We could before, but it had the same behavior as for pointers and didn't make much sense anyway because you can't rebind references so it's good that was removed.