Sign in to follow this  
adder_noir

Reference to a constant pointer

Recommended Posts

adder_noir    275
Hi,

Still reading thru my intermediate book I've hit the latest snag. He's talking about constant pointers and references. Here's the code:

const T *const cpct1 = pt;

.... sometime later

const T &rct = *pt;


now from what I understand he is declaring constant variable 'T'. Then he's declaring a reference which is to be an alias for this variable 'rct'. The next bit *looks* to me like a de-referencing operation. Can I ask though in the first line by declaring a pointer to T 'pt' has he also created an 'object' T. I can't - in the second line - see how I can have a reference aliasing a variable that does not yet exist and I didn't see a 'new' command used anywhere.

Am I talking bull? Help please if possible, thanks ;o)

Share this post


Link to post
Share on other sites
Zao    985
const T *const cpct1 = pt;
declares a variable named
cpctl
of type const-pointer-to-const-T, and assigns it the value of the (assumedly of pointer type) variable pt.

const T &rct = *pt;
declares a variable named
rct
of type reference-to-const-T, and initializes it with the variable at the address pointed to by the pointer pt.

Types are normally read right-to-left to make sense, apart from the wart that a leftmost const is as if it was to the right of the component to the right.

That is, "T const**" and "const T**" are the same type.

Share this post


Link to post
Share on other sites
rip-off    10979
There isn't enough code. It all depends on "pt". The author might be talking about a pointer to an existing T instance (allocated dynamically or on the stack). You don't need to use "new" to get an object:

T instance;

const T *const pointer = &instance;

const T &reference = *pointer;



If "pt" is uninitialised or is NULL, then the line that dereferences it is undefined behaviour.

Also the book is probably terrible if those are the actual variable names it uses.

Share this post


Link to post
Share on other sites
adder_noir    275
Thanks to you both for very good replies. So I wasn't totally out of my tree then! Rip-off you seem a pretty solid guy, can you recommend a decent book then for someone at my experience level. I intentionally went after an intermediate level C++ book. It can be a bit heavy going and a bit weird in places ;o)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this