|
-
February 5th, 2003, 01:55 AM
#1
Difference between reference and const pointer
Can someone tell me the difference between reference and const pointer. Not in the way its used, but the way it is implemented.
My understanding
Reference - Always referes to the same location, but the content can be changed.
Const Pointer - Cannot change the location it points to, but can change the value.
Is that right?
So...
Thanks and Regards
Kannan S
-
February 5th, 2003, 03:33 AM
#2
1. Reference - Can change the referenced object
2. Const-Reference - Can not change the referenced object
3. Const-Pointer - Can change the adress it is pointing to but not the object
4. Pointer-Const - Can change the object but no the address it is pointing to
5. Const-Pointer-Const - Can neither change the address nor the object
Code:
CFoo Instance;
CFoo &ReferenceToInstance = Instance; // 1.
const CFoo &ConstReferenceToInstance = Instance; // 2.
const CFoo *pConstPointer = &Instance; // 3.
CFoo *const pPointerConst = &Instance; // 4.
const CFoo *const pConstPointerConst = &Instance // 5.
-
February 5th, 2003, 04:44 AM
#3
Re: Difference between reference and const pointer
Originally posted by mailtokannan
Can someone tell me the difference between reference and const pointer. Not in the way its used, but the way it is implemented.
My understanding
Reference - Always referes to the same location, but the content can be changed.
Const Pointer - Cannot change the location it points to, but can change the value.
Is that right?
So...
Thanks and Regards
Kannan S
It is irrelevant how references are implemented by a particular compiler. They is likely to be implemented as pointers (or addresses), on the machine code level. But the Standard doesn't specify this, AFAIK.
The difference between a reference and a pointer const is conceptually, at the level of the C++ programming language, despite they behaving very alike.
A reference is the object itself and cannot be resettled (made to referre to another object) no matter what. A pointer const is simply a pointer the compiler consideres to be const.
Thake this piece of code, for example:
Code:
int a = 10;
int &r = a;
int * const p = &a;
const_cast<int *>(p) = &a + 1;
First of all r and a are one and the same object. They refere to the same memory location, as opposed to p, which referes to a memory location that contains the address of a.
The last line of code shows that you actually can change the address p points to -- at least in a way the compiler will accept. Executing the last line of code has undefined results, because, depending on the context, the compiler may choose to place p in a read-only memory area. The example is purely academical, and is a no-no for the daily coding practice.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|