1

How does the call stack look when you initialize a reference with a function return value?

int i = 0;
int &j = i;

I understand that j and i are both pointing to the same memory location.

But when you initialize a reference with a function return value like,

int f();
const int &j = f();

On which stack frame does the memory location referred by j reside? Why does it have to be a const?

Passer By
  • 19,325
  • 6
  • 49
  • 96
Rnet
  • 4,796
  • 9
  • 47
  • 83
  • 1
    It doesn't have to be const, you can do `int&& j = f();`. – M.M Nov 26 '18 at 01:43
  • 1
    These are actually two questions. The second one [has been answered](https://stackoverflow.com/q/2784262/2486888). I am thinking whether the first one should get an "abi" tag. –  Nov 26 '18 at 01:46

2 Answers2

2

j is not a pointer in either case. References are aliases, not pointers.

j in the first case is another name for i.

In the second case, assuming [c++17], reyurning a prvalue (like int) that isn't used to initialize a value results in temporary materialization. If this temporary is directly bound to a reference (in most contexts) the lifetime of the temporary is extended to that of the reference.

temporaries can bind to lvalue references to const (ie int const&), or rvalue references (ieint&&).

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
1

The language does not have a concept of "stack frame". In case of

const int &j = f();

the reference is attached to a temporary object returned by f(). "No one knows" where this temporary object resides. The language does not specify that. However, since its lifetime is extended to match that of the reference, it is probably safe to assume that typical implementations will allocate that temporary in the caller's stack.

As for why the reference has to be const... It is so because the language rules require it. You are not allowed to attach non-const lvalue references to rvalues in C++.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
  • thanks! so when you say "language does not specify that" does that mean it depends on how the compiler chooses to implement it? also what is the rationale for not allowing to attach non-const lvalue references to rvalues? – Rnet Nov 26 '18 at 02:44