473,782 Members | 2,396 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Understanding references

References is a relatively basic feature of C++ language.

It might be a good thing to think of references as aliases to the
variables.
However it's good to think of references this way when you deal with
references which are local variables.
But references can also be function arguments (in fact they are more
useful this way) in which case it has to have the in-memory
representation.

Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).

(BTW please correct if something of what I am saying is wrong. I've
realized that I don't understand references in C although I though I
did.)

So then I asked myself what would return an address-of operator ('&')
applied to a reference. A common sense tells me that it should
basically return a pointer to the value which is referenced. So in
fact it would then have exactly the same value that a reference
variable itself (in terms of in memory storage).

Then I question myself:
1) Is it true that in-memory representation of pointers and references
are the same (i.e. they both contain address to the value the
reference/point)?
2) If the answer to #1 is yes, is it possible to convert from
reference to pointer and vice versa without using "&" and "*"
operators (e.g. with reinterpret_cas t)?
3) Is it true at all that an address-of operator applied to a
reference would return a pointer to a referenced value rather than a
pointer to a reference itself (a reference variable is stored
somewhere in the memory so it has to have its own address)?
4) How can I get a pointer to the piece of memory which contains an
address stored in the reference (i.e. to the reference itself as a
contrast to a pointer to the value referenced by reference)?

Mar 15 '07 #1
9 2472
ig*********@gma il.com wrote:
References is a relatively basic feature of C++ language.

It might be a good thing to think of references as aliases to the
variables.
However it's good to think of references this way when you deal with
references which are local variables.
But references can also be function arguments (in fact they are more
useful this way) in which case it has to have the in-memory
representation.

Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).

(BTW please correct if something of what I am saying is wrong. I've
realized that I don't understand references in C although I though I
did.)
The question "what is a reference" is not answered by the standard. The
standard only specifies how references behave, not how they are
implemented. One can think of the term "reference" as being introduced
axiomatically by the standard.

So then I asked myself what would return an address-of operator ('&')
applied to a reference. A common sense tells me that it should
basically return a pointer to the value which is referenced.
Correct.

So in
fact it would then have exactly the same value that a reference
variable itself (in terms of in memory storage).
There is no such thing. Should a compiler use addresses to implement
references, the location of such an address would still not qualify as
a "variable" since there is no way of observing it from within the program,
i.e., you cannot get at the value of that imaginary variable.

Then I question myself:
1) Is it true that in-memory representation of pointers and references
are the same (i.e. they both contain address to the value the
reference/point)?
The standard does not require in-memory representations of references.

2) If the answer to #1 is yes, is it possible to convert from
reference to pointer and vice versa without using "&" and "*"
operators (e.g. with reinterpret_cas t)?
It is possible, to go from a valid, non-zero pointer to an lvalue using *.
This lvalue can be used to initialize references.

It is possible to obtain a pointer to the object referenced by a reference
using &.

3) Is it true at all that an address-of operator applied to a
reference would return a pointer to a referenced value rather than a
pointer to a reference itself (a reference variable is stored
somewhere in the memory so it has to have its own address)?
There is no "reference variable" required by the standard. Should an
implementation use pointers internally to implement references, then there
still would be no standard way of obtaining the location of such pointers
in memory.

4) How can I get a pointer to the piece of memory which contains an
address stored in the reference (i.e. to the reference itself as a
contrast to a pointer to the value referenced by reference)?
You can't.
The situation is somewhat similar to vtables. The standard does not require
their existence and provides no method of getting at them. If an
implementation uses vtables to implement virtual functions, there still is
no method to access those things.

Also, it is purely psychological whether it helps you to think of references
in terms of a possible implementaion. I don't find it particularly helpful.
I also prefer not to think of virtual functions in terms of vtable entries.
Best

Kai-Uwe Bux
Mar 15 '07 #2
Thanks. That was very helpful.

Mar 15 '07 #3
ig*********@gma il.com wrote:
References is a relatively basic feature of C++ language.

It might be a good thing to think of references as aliases to the
variables.
However it's good to think of references this way when you deal with
references which are local variables.
But references can also be function arguments (in fact they are more
useful this way) in which case it has to have the in-memory
representation.

Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).

(BTW please correct if something of what I am saying is wrong. I've
realized that I don't understand references in C although I though I
did.)

So then I asked myself what would return an address-of operator ('&')
applied to a reference. A common sense tells me that it should
basically return a pointer to the value which is referenced. So in
fact it would then have exactly the same value that a reference
variable itself (in terms of in memory storage).
Right.
Then I question myself:
1) Is it true that in-memory representation of pointers and references
are the same (i.e. they both contain address to the value the
reference/point)?
Informally spoken, yes. As this is an implementation detail, we don't
need to care what the compiler is doing to implement the semantics.

Note that we don't need an in-memory representation of a reference if
the referenced object lives in the same scope as the reference:

int func ()
{
int a;
int& b = a;
int*c = &a;
}

The compiler will certainly reserve only two 16/32/64-bit locations on
the stack, one for variable a and one for c. As b is only an alias for
a, the compiler will certainly only put b in the symbol table, so that a
and b are assigned the same memory location (as pointed out above, this
is an implementation detail, so this information is only relevant for
knowing what happens behind the scenes).
2) If the answer to #1 is yes, is it possible to convert from
reference to pointer and vice versa without using "&" and "*"
operators (e.g. with reinterpret_cas t)?
Nope. As the compiler may not have to reserve memory for a reference
(see above), this operation cannot simply be treated as a casting.
3) Is it true at all that an address-of operator applied to a
reference would return a pointer to a referenced value rather than a
pointer to a reference itself (a reference variable is stored
somewhere in the memory so it has to have its own address)?
Yes.
4) How can I get a pointer to the piece of memory which contains an
address stored in the reference (i.e. to the reference itself as a
contrast to a pointer to the value referenced by reference)?
AFAIK, you can't (as it is not guaranteed that the reference really
needs space like a pointer does).

Regards,
Stuart

Mar 15 '07 #4
On 15 Mar 2007 04:41:42 -0700, igor.kulkin@... com wrote:
>Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).
In order to understand references it is important to remember that C++
was designed as a backward-compatible extension of C. If the C++
language were written from scratch it would not contain overlapping
elements like pointers and references. Being a superset (almost) of C
was a competitive advantage for C++ 15 - 20 years ago but later had
the opposite effect.

Best wishes,
Roland Pibinger
Mar 15 '07 #5
On Mar 15, 4:41 am, igor.kul...@gma il.com wrote:
References is a relatively basic feature of C++ language.

It might be a good thing to think of references as aliases to the
variables.
However it's good to think of references this way when you deal with
references which are local variables.
But references can also be function arguments (in fact they are more
useful this way) in which case it has to have the in-memory
representation.

Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).

(BTW please correct if something of what I am saying is wrong. I've
realized that I don't understand references in C although I though I
did.)

So then I asked myself what would return an address-of operator ('&')
applied to a reference. A common sense tells me that it should
basically return a pointer to the value which is referenced. So in
fact it would then have exactly the same value that a reference
variable itself (in terms of in memory storage).

Then I question myself:
1) Is it true that in-memory representation of pointers and references
are the same (i.e. they both contain address to the value the
reference/point)?
2) If the answer to #1 is yes, is it possible to convert from
reference to pointer and vice versa without using "&" and "*"
operators (e.g. with reinterpret_cas t)?
3) Is it true at all that an address-of operator applied to a
reference would return a pointer to a referenced value rather than a
pointer to a reference itself (a reference variable is stored
somewhere in the memory so it has to have its own address)?
4) How can I get a pointer to the piece of memory which contains an
address stored in the reference (i.e. to the reference itself as a
contrast to a pointer to the value referenced by reference)?
Below is some additional information I pass on to my C++ students
(hopefully it is correct :) ) in regards to references:

Let us start by looking at the following code:

const int & func ( int & ); // function prototype

int main()
{
int A =10;
int B = func(A);
B = 20; // this will not change A's value
return 0;
}

// This function receives int as a "pass by reference" and
// returns the same object as a "return by reference".

const int & func ( int & iref)
{
return iref;
}

Since A of main() is being passed by reference to func(), the address
of A and the address of iref of func() are identical (in other words,
iref references A). It would be a mistake to believe that because
func() is returning iref as a reference, that B also references A. B
will actually receive a copy of the value returned by func(), and
therefore modifying B will not modify A's value.

If we wanted B to reference A, we would need to change the function
call to:

int & B = func(A); // B is now being defined as a reference

Now B references A. But if we rebuild the solution with the change
above, we will get the following error (in MS VS 2003):

: error C2440: 'initializing' : cannot convert from 'const int' to
'int &'

This error occurs because we have specified that the function return
value is const and we are attempting to assign a reference to the
return value that is not const. We can fix this problem by declaring
the reference to be const:

const int & B = func(A); // B is now being defined as a const
reference

But if we make that change, and we rebuild our solution again, we will
now get the following error (in MS VS 2003):

: error C2166: l-value specifies const object

What line of code is the compiler complaining about now? The following
line of code:

B = 20; //attempting to change B's value, which would change A's value
as well!

Now that the reference is const, we are of course not allowed to
change its value. If we were allowed to change B's value, realize
that we would be changing A's as well (since B is a reference to A).

Please note that it is common, as in the example above, when returning
a reference, to declare the returning reference to be const, to
protect the object being returned from being changed.

On to a different, but related, topic. Let us modify func() in the
following way:

const int & func ( int & iref)
{
int X;
...
return X;
}

Is the above change ok?

The answer is no. Why? Because we are attempting to return a reference
to X. But X is an automatic variable and will no longer exist by the
time the reference to X is returned to main(). This is because the
stack frame on which X is stored will have been popped off the
function call stack (read section 6.11 of Deitel & Deitel's "C++ How
To Program" 5th edition for details on how this works).

Will the compiler generate an error?

No. And if the returned value is immediately copied to another
variable in main(), upon returning to main(), the programmer may be
"lucky" and the memory location on the stack where X was stored may
not yet have been overwritten by some other value. In such a case, the
program may appear to work correctly. But this is not a guaranteed
result, and the programmer's "luck" is likely to change at some time
in the future!

If we make the following change, is it ok now?

const int & func ( int & iref)
{
static int X; // X is now static
...
return X;
}

Yes, now we are fine. A static variable, just like a global variable,
is permanent (global variable is created before main() starts
execution, while a static variable is created when the block of code,
in which it is declared, executes for the first time). Therefore it is
now safe to return a reference to X. But realize that we should make
a copy of the returned reference before invoking func() again, since
X's value may be modified when func() is invoked again (thus changing
any variable that references X).

I may have mentioned in class that dynamically created objects
(objects created with the "new" operator) are stored on the "heap" and
that automatic variables (variables of block scope for example) are
stored on the "call stack". Where are static variables (like the last
version of X above) and global variables stored in memory? The answer
is usually in the same general area of memory where your executable
code is stored. Though, some C++ compilers will store static and
global variables on the heap as well.

Mar 15 '07 #6
On Mar 15, 4:41 am, igor.kul...@gma il.com wrote:
Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).
The two important differences between references and pointers are:

1) References can never be null; they can never reference arbitrary
and invalid memory locations. (Well... it might be possible to do
something nasty by creating a reference and then deleting the
original...)

2) Unlike pointers, references are not variables distinct from what is
referenced, and thus cannot be accessed in any way other than the
referenced object.

Your original statement:
It might be a good thing to think of references as aliases to the
variables.
It the better statement. When passed through to functions, I find it
is a better mental exercise to think of reference as an exception to
the scoping paradigm than to think of them as pointers. IE., the scope
of the referenced object has been extended to include this method.

But the best way to think of them is on their own terms. This is a
reference; these are the rules for references; this is how to use
references. No analogies, no mental gymnastics. References are simply
references.

Mar 15 '07 #7
On Mar 15, 1:29 pm, "Bluejack" <bluuj...@gmail .comwrote:
On Mar 15, 4:41 am, igor.kul...@gma il.com wrote:
Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).

The two important differences between references and pointers are:

1) References can never be null; they can never reference arbitrary
and invalid memory locations. (Well... it might be possible to do
something nasty by creating a reference and then deleting the
original...)

2) Unlike pointers, references are not variables distinct from what is
referenced, and thus cannot be accessed in any way other than the
referenced object.

Your original statement:
It might be a good thing to think of references as aliases to the
variables.

It the better statement. When passed through to functions, I find it
is a better mental exercise to think of reference as an exception to
the scoping paradigm than to think of them as pointers. IE., the scope
of the referenced object has been extended to include this method.

But the best way to think of them is on their own terms. This is a
reference; these are the rules for references; this is how to use
references. No analogies, no mental gymnastics. References are simply
references.
Let me add 3) to the list above:

3) In C++, whatever object a reference is initialized to be reference
to, that is the object it will reference for the life of the reference
(I beleive this may not be case in all programming languages that
support references). Pointers on the other hand, can be made to point
to several different ojects during the lifetime of the pointer (unless
the pointer is const).

Mar 15 '07 #8
On Mar 15, 1:40 pm, "blangela" <Bob_Langel...@ telus.netwrote:
On Mar 15, 1:29 pm, "Bluejack" <bluuj...@gmail .comwrote:


On Mar 15, 4:41 am, igor.kul...@gma il.com wrote:
Today it just hit me that references are much like pointers in a way
the it's a variable that stores a pointer to a piece of memory. It's
just that the syntax of using references is a little bit different
from using pointers (we don't need to dereference (dereference is a
little bit misleading here. I mean indirection operator "*".) it each
time we want to access the value to which it points).
The two important differences between references and pointers are:
1) References can never be null; they can never reference arbitrary
and invalid memory locations. (Well... it might be possible to do
something nasty by creating a reference and then deleting the
original...)
2) Unlike pointers, references are not variables distinct from what is
referenced, and thus cannot be accessed in any way other than the
referenced object.
Your original statement:
It might be a good thing to think of references as aliases to the
variables.
It the better statement. When passed through to functions, I find it
is a better mental exercise to think of reference as an exception to
the scoping paradigm than to think of them as pointers. IE., the scope
of the referenced object has been extended to include this method.
But the best way to think of them is on their own terms. This is a
reference; these are the rules for references; this is how to use
references. No analogies, no mental gymnastics. References are simply
references.

Let me add 3) to the list above:

3) In C++, whatever object a reference is initialized to be reference
to, that is the object it will reference for the life of the reference
(I beleive this may not be case in all programming languages that
support references). Pointers on the other hand, can be made to point
to several different ojects during the lifetime of the pointer (unless
the pointer is const).- Hide quoted text -

- Show quoted text -
I might have added: "Which is why a reference _MUST_ be initialized at
the point it is defined, just as with a const pointer."

Mar 15 '07 #9
On Thu, 15 Mar 2007 16:12:41 GMT, rp*****@yahoo.c om (Roland Pibinger) wrote:
>In order to understand references it is important to remember that C++
was designed as a backward-compatible extension of C. If the C++
language were written from scratch it would not contain overlapping
elements like pointers and references. Being a superset (almost) of C
was a competitive advantage for C++ 15 - 20 years ago but later had
the opposite effect.
I doubt C had anything to do with it. References and pointers serve different
purposes. Languages that lack a distinction between references and pointers
(like Java) live in denial--they just call both constructs the same thing, and
deal with the problems of both paradigms all the time. They also make it
difficult to deal with the low-level operations needed for high performance
code, which are the forte of pointers.

-dr
Mar 16 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4204
by: Marty McDonald | last post by:
If I invoke a web service, and it throws an exception, I can see the exception if the client app is a .Net app. However, if the client app is not a .Net app, I only receive the HTTP 500 error. I believe this is due mostly to the fact that the non-.Net apps are using POST instead of SOAP. If the non-.Net apps were using SOAP, they too would in fact "see" the exception. Is this true? Thanks!
2
1401
by: rodchar | last post by:
hey all, i have a simple app that references the web.config. i browse to the page. i changed the web.config. i do a postback to the page, And session is gone. Only after i close the browser and reopen it start working with the new settings.
3
2000
by: Miguel | last post by:
Hi, I'm new to .NET and am using VB .NET as I am from a VB background. I am having difficulty understanding the way .NET handles, passes and uses objects. I have had a look at the Micrsoft Data Access Application blocks for .NET and am struggling to understand the following: 1. When creating a function that returns a datareader, there is a datareader instantiated inside the function. This datareader is then returned to the
5
1434
by: Irfan Mumtaz | last post by:
hi, I had posted a question in the group "how to arrange arrays in increasing order" Although i got an answer using IComparable Interface by Harfried ,which is given below. Dim InputArray()() As Integer = _ New Integer()() { _ New Integer() {2, 0, 0}, _ New Integer() {1, 0, 0}, _ New Integer() {6, 0, 0}, _ New Integer() {3, 0, 0} _
18
2200
by: Simon | last post by:
Hi, I understand what one the differences between std::vector, std::deque and std::list is, the std::vector can have data inserted/deleted at the end. The std::deque can have data inserted/deleted at the end and at beginning and the std::list can have data inserted/deleted anywhere. But how can those differences be physically understood?
3
4412
by: Richard Lewis Haggard | last post by:
We are having a lot of trouble with problems relating to failures relating to 'The located assembly's manifest definition with name 'xxx' does not match the assembly reference" but none of us here really understand how this could be an issue. The assemblies that the system is complaining about are ones that we build here and we're not changing version numbers on anything. The errors come and go with no apparent rhyme or reason. We do not...
13
3025
by: Chris Carlen | last post by:
Hi: I have begun learning Python by experimenting with the code snippets here: http://hetland.org/writing/instant-python.html In the section on functions, Magnus Lie Hetland writes: -------------------------------------------------------------------- For those of you who understand it: When you pass a parameter to a
5
1887
by: arnuld | last post by:
it works fine: /* C++ Primer - 4/e * * example from section 7.2.2, pointer-swap * STATEMENT * in a function call where parameters are pointers, we actually copy the pointers. * here in this example we are using the original pointers. *
5
1875
Nepomuk
by: Nepomuk | last post by:
Hi! I'm learning C++ and have just read about Pointers and References a bit. Now I'm not absolutely sure, that I've understood it correctly. I asume, that (taking an example from the real world) "nepomuk" would be a reference to me, and I could have further references like "other_name" or so, that also refer to me. And of course, if you would annoy "other_name", it would also affect "nepomuk". person nepomuk = new person(...); person &...
0
9641
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10146
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10080
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.