Const-correctness issues

Hello again,

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 const int * 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 const int * 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?

Thanks!
Last edited on
closed account (1yR4jE8b)
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.
Last edited on
That's what I assumed the const after the & did, but since it seemed so redundant it didn't make sense. Any idea why this is allowed?
Last edited on
First, second are the same. The 3rd is probably also the same, although a bit weird, not sure if you can have that many consts, but it's probably ok.

FYI,
1
2
const int x;
int const y;

are the same.
closed account (1yR4jE8b)
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.
Last edited on
Ok, got it, thanks!
Topic archived. No new replies allowed.