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

Home Posts Topics Members FAQ

REFERENCES REVEALED


I understand variables/objects and pointer variables perfectly:

int X = 5;

int* pX = &X;

*pX = 4;

int** ppX = &pX:

**ppX = 3;
---

I know exactly how references "behave", but I want to know how they actually
work!

For instance, take the following function:

void Repot(unsigned int* pX)
{
*pX = 45U;
}
The caller will do the following:

int main(void)
{
unsigned int X = 17U;

Repot(&X);
}
Obviously one could rewrite the above code as:
void Repot(unsigned int& X)
{
X = 45U;
}
int main(void)
{
unsigned int X = 17;

Repot(X);
}
But what I want to know is what's actually going on under the hood. One
quick little side note here though before I continue: When I first learned
about references, I detested them, I thought they were extremely stupid. One
may argue that they're easier to use, just as one may argue that an
automatic transmission car is easier to driver, but long story short, I
prefer manual transmission and detest references. So anyway, I could find no
justification for the introduction of references into C++, other than to
make operator overloading for classes possible. I was pleasantly amused when
I heard a quote from Bjarne himself stating that the reason he introduced
references into C++ was to enable operator overloading for classes. Fair
enough, and although in my opinion it is heavily contrived, it works! Just
for clarification, here's what I hate so much about references: Before, when
calling a function, you could specify "X" to indicate the value stored in
the variable, and you could specify "&X" to indicate the memory address of
the variable. With references, this is no longer so. (Yes, I am aware that
one can determine from the function prototype whether or not it's a
reference... I don't like it).

So anyway, how does the compiler deal with references? Does it simply treat
them as short-hand? Would the compiler turn my preceeding code (written
using references) back into pointers? ie. would it simply stick in the "*"
and "&" where appropriate? If the answer to this is Yes, then I pressume
that both samples of code would compile identically and hence allocate the
same amount of memory. (That is, the use of a reference does not supress the
need to have another variable within which to store the address of another
variable, ie. a pointer variable). If this is so, everything is fine and
dandy and I understand references, regardless of whether I like them. If
this is NOT so, I am at a loss! Before, I used to just think of it as
follows: If a function has a reference as a parameter, then you can think of
it as the scope of the variable being extended to the function which has
been called. This concept worked fine for me until I came across functions
whose return type was a reference. This is where my brain started
stuttering. Take the function prototype:

unsigned int& TeachFarmAnimal s(void);

When you call the above function, what exactly are you getting back as a
return type?!! Are you simply receiving a pointer, and is the compiler just
sticking in the "*" and "&" for you where appropriate?
In summation:

Are references just pointers without the need to include "&" and "*", and is
the compiler just handling the "&" and "*" for you in the background?
-JKop
Jul 22 '05 #1
33 2403
On Sun, 16 May 2004 19:19:54 GMT, JKop <NU**@NULL.NULL > wrote in
comp.lang.c++:

I understand variables/objects and pointer variables perfectly:

int X = 5;

int* pX = &X;

*pX = 4;

int** ppX = &pX:

**ppX = 3;
---

I know exactly how references "behave", but I want to know how they actually
work!
They work very well, thank you.

[snip]
But what I want to know is what's actually going on under the hood.


Unfortunately, you are asking in the wrong place. The C++ standard
does not specify what goes on "under the hood". The standard defines
the interface to the programmer and the behavior when used correctly.
It places no requirements at all on the implementation as to how it
delivers the correct results. Nor is it necessary to for one to know
the details to write a correct C++ program.

If you want to understand how a specific compiler does these things,
study the object code it generates. If you want to discuss the
possible mechanisms in general, try news:comp.compi lers.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jul 22 '05 #2

"JKop" <NU**@NULL.NULL > wrote in message
news:u9******** **********@news .indigo.ie...

I understand variables/objects and pointer variables perfectly:

int X = 5;

int* pX = &X;

*pX = 4;

int** ppX = &pX:

**ppX = 3;
---

I know exactly how references "behave", but I want to know how they actually work!

For instance, take the following function:

void Repot(unsigned int* pX)
{
*pX = 45U;
}
The caller will do the following:

int main(void)
{
unsigned int X = 17U;

Repot(&X);
}
Obviously one could rewrite the above code as:
void Repot(unsigned int& X)
{
X = 45U;
}
int main(void)
{
unsigned int X = 17;

Repot(X);
}
But what I want to know is what's actually going on under the hood. One
quick little side note here though before I continue: When I first learned
about references, I detested them, I thought they were extremely stupid. One may argue that they're easier to use, just as one may argue that an
automatic transmission car is easier to driver, but long story short, I
prefer manual transmission and detest references. So anyway, I could find no justification for the introduction of references into C++, other than to
make operator overloading for classes possible. I was pleasantly amused when I heard a quote from Bjarne himself stating that the reason he introduced
references into C++ was to enable operator overloading for classes. Fair
enough, and although in my opinion it is heavily contrived, it works! Just
for clarification, here's what I hate so much about references: Before, when calling a function, you could specify "X" to indicate the value stored in
the variable, and you could specify "&X" to indicate the memory address of
the variable. With references, this is no longer so. (Yes, I am aware that
one can determine from the function prototype whether or not it's a
reference... I don't like it).
You're missing out on two important aspect of references, one aesthetic, one
practical.

From the aesthetic point of view the chief difference between pointers and
references is that references always refer to the same object, unline
pointers. So if you need to refer to some object, and that reference (in the
general sense) is never going to refer to another object during its lifetime
you should consider using a reference (in the C++ sense) because it better
expresses what you are doing.

From the practical point of view there is the fact that a const reference
can bind to a temporary, something a pointer cannot do. Consider

class X;

void f1(const X*);
void f2(X);
void f3(const X&);
X g();

f1(&g()); // illegal

X t = g();
f1(&t); // ugly temp variable, extra copy

f2(g()); // extra copy, may or may not be optimised by compiler

f3(g()); // perfect


So anyway, how does the compiler deal with references? Does it simply treat them as short-hand? Would the compiler turn my preceeding code (written
using references) back into pointers? ie. would it simply stick in the "*"
and "&" where appropriate?


Almost certainly, so certain am I that I've always assumed this to be the
case on every compiler I've ever used, and haven't actually bothered to
check. The only way to be sure would be to have a look at the machine code
your compiler generates.

john
Jul 22 '05 #3


I finally understand reference variables perfectly!! It's the way that they
were described to me that had me all confused. The books I've learned from
have never just stated plainly:

A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
It's like a const pointer variable, ie. you must initialize it upon
declaration:

int m = 5;

int* const pM = &m;

int& j = m;
Andt the second and final difference is that you treat it like a normal
variable, ie. you don't use the asterisk to access its data. And again, like
a normal variable, if you get the address of it, you get back an "int*", as
opposed to an "int**". It's so clear in my mind now. I fully understand:

Car& Porsche = *(new Car);

delete &Porsche;
and it's much more beautiful than:

Car* pPorsche = new Car;

delete pPorsche;
That is, you can work with a "Car", and not with a "Car*"!!
And similarly, when a function returns a reference:

int& GetApe(void);
It's returning a const pointer that you can treat as an "int" as opposed to
an "int*".
John Harrison, you said that an reference can also bind to a temporary, and
that's cool too, but just for clarity, so can a pointer. Consider the
following tested code:
long double Monkey(void)
{
return 87.343;
}

void Chocolate(long double* pTermite)
{
*pTermite = 56.242;

std::cout << *pTermite;
}

int main(void)
{
long double k;

Chocolate(&(k = Monkey()));

system("PAUSE") ;
return 0;
}

The temporary in the above is valid, right?
-JKop

Jul 22 '05 #4
JKop posted:
John Harrison, you said that an reference can also bind to a temporary,
and that's cool too, but just for clarity, so can a pointer. Consider
the following tested code:
long double Monkey(void)
{
return 87.343;
}

void Chocolate(long double* pTermite)
{
*pTermite = 56.242;

std::cout << *pTermite;
}

int main(void)
{
long double k;

Chocolate(&(k = Monkey()));

system("PAUSE") ;
return 0;
}

The temporary in the above is valid, right?

I TOTALLY dropped the ball there!! I'm making a copy of the temporary via:

k = Monkey();
Duh!!!
I see what you're getting at, John Harrison, that you simply can't get the
address of a temporary, ie:

&(Monkey())

The above doesn't compile. Yet, a reference *will* get the address!!
-JKop
Jul 22 '05 #5
JKop writes:
I finally understand reference variables perfectly!! It's the way that they were described to me that had me all confused. The books I've learned from
have never just stated plainly:

A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
A reference variable is just a pointer variable.


What so you call a variable that can't be changed in your world?
Jul 22 '05 #6
osmium posted:
JKop writes:
I finally understand reference variables perfectly!! It's the way that
they were described to me that had me all confused. The books I've
learned from have never just stated plainly:

A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
A reference variable is just a pointer variable.


What so you call a variable that can't be changed in your world?


Ignoring your grammar...
I was given vague descriptions like so:
A reference is used so a function can edit the variable passed to it:

void Monkey(int& j)
{
j = 5;
}
It never actually just stated that a reference is just a const pointer
variable that's treated like a domestic non-pointer variable.

-JKop
Jul 22 '05 #7
JKop wrote:

I finally understand reference variables perfectly!! It's the way that they
were described to me that had me all confused. The books I've learned from
have never just stated plainly:

A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
A reference variable is just a pointer variable.


Wrong.
A reference is just another name for a variable.

Your compiler might use a pointer internally to represent it, but
it need not. Nevertheless the thinking model of a 'hidden pointer'
is a good one. But there is a difference between a mental model
and what things really are. References are alternative names.
--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #8
Karl Heinz Buchegger wrote:

JKop wrote:

I finally understand reference variables perfectly!! It's the way that they
were described to me that had me all confused. The books I've learned from
have never just stated plainly:

A reference variable is just a pointer variable.
A reference variable is just a pointer variable.
A reference variable is just a pointer variable.


Wrong.
A reference is just another name for a variable.


Also wrong:

A reference is just another name for an object (it need not be a variable)

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #9
Karl Heinz Buchegger posted:
Wrong.
A reference is just another name for a variable.

Your compiler might use a pointer internally to represent it, but
it need not. Nevertheless the thinking model of a 'hidden pointer'
is a good one. But there is a difference between a mental model
and what things really are. References are alternative names.

struct Jeep
{
std::Vector& a;
std::Vector& b;
};
Then explain the above. If it's just another name for a variable, then what
the hell are a and b ?

Pointers is what they are, and on a 32-Bit Memory Model platform, sizeof
(Jeep) will be 64 Bits, which proves my point.
int main(void)
{
Vector j;
Vector k;

Jeep jeep = {j, k};
}
Jul 22 '05 #10

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

Similar topics

22
2244
by: xmp333 | last post by:
Hi All, I am trying to hide my JavaScript source. The method I chose was to keep all the important source in a password protected folder, and then use a SRC="folder/script.js" to include it in my code. This way, the script will run, but the user will be unable to view the included code. Or so I think :). I have tried this method, and it seems to work. However, I would like
354
15927
by: Montrose... | last post by:
After working in c# for a year, the only conclusion I can come to is that I wish I knew c. All I need is Linux, the gnu c compiler and I can do anything. Web services are just open sockets hooked up to interfaces. The Gtk is more than enough gui.
2
32207
by: Michelle Collier-Moore | last post by:
Please could someone offer some advice regarding adding references to an Access database? I tried to open a project a few days ago sent to me by someone whose developer had left the company. I found that I had a reference problem and went to the usual Tools, References place to fix it. The References option was greyed out and as I have never seen this happen before, after trying various things, searching here for an answer etc. gave up!!
2
22292
by: S. van Beek | last post by:
Dear reader, For removing a reference in the VBA reference form I receive from Doug Steele the following code: ........... References.Remove refCurr
9
1335
by: Xah Lee | last post by:
in coding Python yesterday, i was quite stung by the fact that lists appened to another list goes by as some so-called "reference". e.g. t=range(5) n=range(3) n='m' t.append(n) n='h' t.append(n) print t
30
2487
by: jeremygetsmail | last post by:
I've got an adp (Metrix.adp) with a reference to another adp (InteractSQL.adp). InteractSQL sits on a server, and is refered to by all of the clients (Metrix), which sit on the client machines (There's also a SQL Server that sits on the server, but that's besides the point here.). Both adp files have references to ADOX. I've got to check Metrix has an older version of ADOX, and react appropriately. I've written code to do this, and it...
9
2472
by: igor.kulkin | last post by:
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.
76
4719
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the pointers are allowed to be null, while references must refer an existing variable of required type. The null is normally used for making optional parameters. But there is no way to pass null reference in C#. Something is missing.
29
35504
weaknessforcats
by: weaknessforcats | last post by:
Arrays Revealed Introduction Arrays are the built-in containers of C and C++. This article assumes the reader has some experiece with arrays and array syntax but is not clear on a )exactly how multi-dimensional arrays work, b) how to call a function with a multi-dimensional array, c) how to return a multi-dimensional array from a function, or d) how to read and write arrays from a disc file. Note to C++ programmers: You should be using...
0
9639
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
9479
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10311
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
9942
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7492
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
6733
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
5509
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4043
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
3639
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.