According to the following program, I can understand that, const
keyword at a front of a references means Const Reference to const value
, correct?
#include <iostream>
using namespace std;
struct s
{
int x;
};
int main(void)
{
s a = {10}, b = {30};
// IN POINTERS ----------------
const s* ptrToConstValue;
ptrToConstValue= &a;
//ptrToConstValue->x = 30;
ptrToConstValue = &b;
s* const constPtrToNonConstVaue = &a;
constPtrToNonConstVaue->x = 40;
//constPtrToNonConstVaue = &b;
const s* const constPtrToConstValue = &a;
//constPtrToConstValue = &b;
//constPtrToConstValue->x = 30;
// IN REFERENCES -------------
const s& seemsToBeConstRefToConstValue = a;
//s = b;
//s.x = 30;
return 0;
}
Const pointers can be NULL. A reference does not have its own address whereas a pointer does. The address of a reference is the actual object's address. A pointer has its own address and it holds as its value the address of the value it points to.
Memory Address: A pointer has its own memory address and size on the stack, whereas a reference shares the same memory address with the original variable but also takes up some space on the stack.
Once a reference variable has been defined to refer to a particular variable it can refer to any other variable. A reference is not a constant pointer.
A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const. Once a reference is bound to refer to an object, it can not be bound to refer to another object.
So the confusion is this:
X x;
X* px = &x; // pointer to x
X* const px = &x; // *const pointer* to x
const X* px = &x; // pointer to *const x*
X const* px = &x; // identical
const X* const px = &x; // *const pointer* to *const x*
Now in reference, the 'pointer part' is always const:
X& rx = x; // ref to x
X const& rx = x; // ref to const x
const X& rx = x; // identical
References are always const, so you don't need the const
keyword for
them; it is, in fact, forbidden.
So you have:
S* ps; // Non-const pointer to a non-const value
S const* psc; // Non-const pointer to a const value
S* const pcs; // Const pointer to a non-const value
S const* const pcsc; // Const pointer to a const value
, but only:
S& rs; // (const) reference to a non-const value
S const& rsc; // (const) reference to a const value
The const
which immediately follows the name of the type can be moved
to the beginning of the declaration, at the cost of some confusion to
the reader.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With