0

Consider these 2 files:

//main1.cpp

int main()
{
    int a = 0;
    int &b = a;
}

//main2.cpp

int main()
{
    int a = 0;
    int *b = &a;
}

And when I compile it with gcc -S option and compare 2 assembler outputs, they were exactly same outputs. So why do some books say that reference variables does not use extra memory?

Eduard Rostomyan
  • 7,050
  • 2
  • 37
  • 76
  • Compiler-specific optimation perhaps... – Lynn Crumbling May 21 '15 at 14:32
  • 4
    "So why some books say that reference variables does not extra memory??" Because they don't know what they're talking about. Get a [better book](http://stackoverflow.com/questions/388242). (Also, for an example like this, all the code is probably removed since it doesn't do anything). – Mike Seymour May 21 '15 at 14:32
  • 4
    Semantically, references do not need to occupy memory. They certainly don't have an address. But under the hood, pointers may be used by the implementation if necessary. The implementation can do whatever it needs in order to produce the required semantics. – juanchopanza May 21 '15 at 14:36

1 Answers1

10

It's unspecified whether or not a reference takes up memory. If the compiler can determine which object it refers to, then it can simply use the reference as an alternative "name" for that object, with no need for any run-time information. If it can't, then the reference will need to hold its target's address, just like a pointer.

Pointers are objects, and so take up memory like any other object. However, optimisations under the "as if" rule mean that objects only have to take up memory if the program's behaviour depends on them doing so; for example, if you print its address. So if the compiler can determine which object the pointer points to, then it can replace indirect accesses through the pointer with direct accesses to that object, and perhaps remove the pointer altogether.

The same optimisation rule means that, in both your examples, all the variables can be removed since they have no effect.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644