Rnet
Rnet

Reputation: 5040

How does the call stack look when you initialize a reference from a function return value in C++?

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?

Upvotes: 1

Views: 140

Answers (2)

AnT stands with Russia
AnT stands with Russia

Reputation: 320531

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++.

Upvotes: 1

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

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&&).

Upvotes: 2

Related Questions