Reference to a constant pointer

Started by
2 comments, last by adder_noir 13 years, 6 months ago
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 laterconst 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)
Advertisement
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.

To make it is hell. To fail is divine.

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.
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)

This topic is closed to new replies.

Advertisement