Referencing const objects/pointers in C++

Go To StackoverFlow.com

1

There's something I don't quite understand with how references are handled in C++:

B objB = B();                   // Regular B object
const B &refConstObjB = objB;   // Reference to const B object

B* ptrB = new B();              // Regular pointer to B
B* const &refPtrConstB = ptrB;  // Reference to const pointer to B 

All of the above compiles just fine. However the following doesn't:

const B* &refConstPtrB = ptrB;  // Reference to pointer to const B

Considering both the object and the pointer were declared as non-const, why can I reference the object as a const object, but can't do the same with the pointer?

2012-04-05 02:30
by RedsChineseFood
By the way, my variable names are wrong! refConstPtrB and refPtrConstB should be inverted - RedsChineseFood 2012-04-05 03:07


2

Just to note: A const reference does not imply a const object.
It simply means an object that is read-only through that reference. So whether or not an object is const, you can have a read-only reference or pointer to it.

Now, if what you mentioned were allowed, you could say refConstPtrB = pointer_to_some_const_B, and then mutate that object through ptrB, which would violate the const-ness of the pointer's target.

2012-04-05 02:36
by Mehrdad
I see! Declaring refConstPtrB give us no guarantee that the data that is being pointed is constant. I would have to declare a pointer to a constant B object for refConstPtrB to be legal. I should have spotted this! Oh well, I guess I'm tired - RedsChineseFood 2012-04-05 03:04


1

The reason for this error is that you can put a hole in the type system with it. Consider the following code:

const B dontChangeMe;
B* ptrB = new B();

/* This step is NOT legal. */
const B* &refConstPtrB = ptrB;

/* Uh oh!  I now have ptrB pointing at dontChangeMe! */
refConstPtrB = &dontChangeMe;

Consequently, you can't do the assignment that you marked.

Hope this helps!

2012-04-05 02:35
by templatetypedef
Ads