473,792 Members | 2,796 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
33 2404
Can anyone here suggest any reason at all why the following expression would
be false?:
sizeof(BankAcco untInfoPointers ) == sizeof(BankAcco untInfoReferenc es)

Because sizeof(---Pointers) has to be the size of a number (16,32,64
bits). sizeof(---References) could well result in giving you the size
of the object it refers to.

This isn't an ignorant rhetorical question, I'm genuinely interested in a
possible reason, other than "'cause the Standard doesn't says it has to be".

But that is the reason you have to weight the most. If the standard
does not guarantee this, and there is a clever way of implementing
reference behavior that is not based on pointers, all your underlying
assumptions will be lost.

If yu had a car before the 80s, you would have probably assumed that the
only way to pump gas is through a carburator. Nowadays, this is rarely
true. What I mean is, the fact that references are implemented as
pointers today does not guarantee that it always will, and you MUST
realize this.

Stop arguing. What's the point?

Jorge L.
Jul 22 '05 #21
Mabden wrote:

"Jorge Rivera" <jo*****@roches ter.rr.com> wrote in message
news:mH******** ***********@twi ster.nyroc.rr.c om...
Can anyone here suggest any reason at all why the following expression would be false?:
sizeof(BankAcco untInfoPointers ) == sizeof(BankAcco untInfoReferenc es)


Because sizeof(---Pointers) has to be the size of a number (16,32,64
bits). sizeof(---References) could well result in giving you the size
of the object it refers to.

This isn't an ignorant rhetorical question, I'm genuinely interested in a possible reason, other than "'cause the Standard doesn't says it has to be".

But that is the reason you have to weight the most. If the standard
does not guarantee this, and there is a clever way of implementing
reference behavior that is not based on pointers, all your underlying
assumptions will be lost.

If yu had a car before the 80s, you would have probably assumed that the
only way to pump gas is through a carburator. Nowadays, this is rarely
true. What I mean is, the fact that references are implemented as
pointers today does not guarantee that it always will, and you MUST
realize this.


Ah. So, altho they probably ARE const pointer right now,


They CAN be.
But the ARE NOT.

A reference may exist in the symbol table of your compiler
only.
When your compiler encounters this piece of code:

int main()
{
int i;
int& j;

it creates 2 entries in its symbol table, one for i, one for j.
The point is: The compiler marks j as beeing a reference to i.
Now when the compiler compiles

j = 5;

It looks up j in its internal symabol table and figures out that
j is an alias for i. So the compiler modifies the statement
to read

i = 5;

and compiles that instead.

In the final exacutable, j doesn't even show up and this has nothing
to do with some optimizations. It's just a consequence of: a reference
is another name to an already existing object.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #22
JKop wrote:

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 ?


References.

Pointers is what they are, and on a 32-Bit Memory Model platform, sizeof
(Jeep) will be 64 Bits, which proves my point.


Which proves exactly nothing.
An example is not a proof.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #23
JKop <NU**@NULL.NULL > 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.
I should hope not, since they would be wrong.
Look man, several people with many years of practical C++ experience
have told you that you are wrong. Maybe you should start listening to them?
struct Jeep
{
std::Vector& a;
std::Vector& b;
};

int main(void)
{
Vector j;
Vector k;

Jeep jeep = {j, k};
} Then explain the above. If it's just another name for a variable, then what
the hell are a and b ?
'a' and 'b' are other names for variables, as you say.

If you consider this slightly modified (and compilable) example:

struct Jeep
{
std::vector<int > &a;
Jeep(std::vecto r &a_): a(a_) {}
};

int main()
{
std::vector<int > v;
Jeep j(v);

j.a.push_back(1 0);
v.push_back(12) ;
}

"j.a" and "v" mean exactly the same thing. If you picture the memory
location of the vector in your mind, think of it as having two labels
"j.a" and "v". These two terms are completely interchangeable , in
any expression. If you think about it for a moment, you would realise
that the same is not true of pointers.

Pointers is what they are, and on a 32-Bit Memory Model platform, sizeof
(Jeep) will be 64 Bits, which proves my point.


It would be difficult for the compiler to maintain a list of which
label refers to which object, by any means other than storing the
address of that object with that label. Implementations use addresses
internally when remembering what references are bound to.

Implementation details do not "prove your point". (On one of my
systems, sizeof(int) is 2. Does this prove that ints have 16 bits?)

It's good that you have something in mind that gives you a better
handle on references. But you should bear in mind that this is
an imperfect description, and you will become confused in future
when you encounter problems with it. For example, as you pointed
out yourself,

int Monkey() { return 42; }
int main()
{
int const &k = Monkey();
std::cout << k << std::endl;
return 0;
}

How would you write that with const pointers? What is &k?

It's like the "dump-truck" analogy for electricity (each electron is
loaded up with power, and as it passes through the bulb, it dumps all
its power so the bulb glows). Seems like a good idea, but is actually
totally wrong, and worse than useless.
Jul 22 '05 #24
int Monkey() { return 42; }
int main()
{
int const &k = Monkey();
std::cout << k << std::endl;
return 0;
}

You're accessing unallocated memory there - the temporary no longer
exists.
-JKop
Jul 22 '05 #25
John Harrison posted:

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

int Monkey(void) { return 42; }
void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}
int main(void)
{

int* k;
Parrot( &( *k = Monkey() ) );
system("PAUSE") ;

}

I love it!

If anyone could post something from the Standard regarding the lifetime of
temporaries, I'd appreciate it. As far as I know, the above is valid, ie.
DEFINED BEHAVIOUR!
-JKop
Jul 22 '05 #26
JKop wrote in news:bi******** *********@news. indigo.ie in comp.lang.c++:
John Harrison posted:

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

int Monkey(void) { return 42; }
void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}
int main(void)
{

int* k;


k points where ?

Parrot( &( *k = Monkey() ) );
You've just writen (*k =) the value 42 to some random location.

This is Undefined Behavior.


system("PAUSE") ;

}

I love it!
Whats to love ?

If anyone could post something from the Standard regarding the
http://www.techstreet.com/cgi-bin/de...uct_id=1143945
lifetime of temporaries, I'd appreciate it. As far as I know, the
above is valid, ie. DEFINED BEHAVIOUR!


No its UB.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #27
JKop wrote:
int Monkey() { return 42; }
int main()
{
int const &k = Monkey();
std::cout << k << std::endl;
return 0;
}

You're accessing unallocated memory there - the temporary no longer
exists.


He is not.
JKop you have posted since a few days and some of your posts
are really good. But your knowledge is weak. There are a few
regulars in this group you should listen to. You can only learn
from them.

As why the above is not accessing unallocated memory:
When a temporary is bound to a reference, the lifetime
of the temporary is also bound to the lifetime of the
reference. The temporary lives as long as the reference
lives.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #28
JKop wrote:

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


int Monkey(void) { return 42; }

void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}

int main(void)
{

int* k;
Parrot( &( *k = Monkey() ) );
system("PAUSE") ;

}

I love it!

If anyone could post something from the Standard regarding the lifetime of
temporaries, I'd appreciate it. As far as I know, the above is valid, ie.
DEFINED BEHAVIOUR!


Take more care!
The above is undefined behaviour. Where does k point to when you
dereference it. Just because it compiles and runs at your system
doesn't mean it is correct.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #29
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
news:40******** *******@gascad. at...
JKop wrote:

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


int Monkey(void) { return 42; }

void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}

int main(void)
{

int* k;
Parrot( &( *k = Monkey() ) );
system("PAUSE") ;

}

I love it!

If anyone could post something from the Standard regarding the lifetime of temporaries, I'd appreciate it. As far as I know, the above is valid, ie. DEFINED BEHAVIOUR!


Take more care!
The above is undefined behaviour. Where does k point to when you
dereference it. Just because it compiles and runs at your system
doesn't mean it is correct.

Sorry for the quote-to-comment ratio, but WTF?!!

Can you guys figure it out and post the actual truth about how this works? I
don't know enough to figure it out and you are getting less helpful as you
post snipettes. Somebody please summarize the argument and explain how
pointers (or const pointer) and references differ in the Real World (tm).

--
Mabden
Jul 22 '05 #30

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

Similar topics

22
2247
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
15928
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
22293
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
1336
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
2490
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
2474
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
4720
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
35507
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
9518
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
10211
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
10159
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,...
0
10000
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...
0
9033
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
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
6776
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
5436
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2917
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.