Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the low-level difference between a pointer an a reference?

If we have this code:

int foo=100;
int& reference = foo;
int* pointer = &reference;

There's no actual binary difference in the reference's data and the pointer's data. (they both contain the location in memory of foo)

part 2

So where do all the other differences between pointers and references (discussed here) come in? Does the compiler enforce them or are they actually different types of variables on the assemebly level? In other words, do the following produce the same assembly language?

foo=100;
int& reference=foo;
reference=5;

foo=100;
int* pointer=&foo;
*pointer=5;
like image 621
Gordon Gustafson Avatar asked Oct 28 '09 21:10

Gordon Gustafson


People also ask

What's the difference between a pointer and a reference?

References are used to refer an existing variable in another name whereas pointers are used to store address of variable. References cannot have a null value assigned but pointer can. A reference variable can be referenced by pass by value whereas a pointer can be referenced by pass by reference.

What is the difference between a pointer value and a pointer reference?

Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.

What is a pointer referencing?

A reference to a pointer is a modifiable value that's used like a normal pointer.

Are references slower than pointers?

Reference vs Pointer in C++. As a rule of thumb, passing by reference or pointer is typically faster than passing by value, if the amount of data passed by value is larger than the size of a pointer. . In this case, they are equivalent. References have clearer semantics.


1 Answers

Theoretically, they could be implemented in different ways.

In practice, every compiler I've seen compiles pointers and references to the same machine code. The distinction is entirely at the language level.

But, like cdiggins says, you shouldn't depend on that generalization until you've verified it's true for your compiler and platform.

like image 121
Crashworks Avatar answered Nov 16 '22 02:11

Crashworks