We got practice sheets for a test next week, for studying a little bit of C++ (still a beginner here). I still can\'t figure out a simple question.
That is, why are thes
Both snippets pass a reference (or pointer in the second case) to temporary. Consider for example p(18)
. Where would 18 actually be stored? So where should p(18)
point to?
Side note: If everything would be const, the code would be ok, ie.
int const & p(int const & input) { return input; }
The standard would guarantee it.
The behavior of the returned value is undefined.The tricky thing here is that if you test your function with some kind of operation ( eg. printing to std output or assertion) you might often get an expected result but that doesn't mean it is safe since returned value is pointing to value written in the stack which could be wiped out at any given moment right after the function returns ( it is called stack unwinding). So, the rule of thumb is, don't return the address or reference to a locally defined variable of a function unless it was defined as static and why on earth would one prefer that unless situations force you? :-)
When int *h(int z) {return &z}
is called, the parameter passed to the function is copied to a variable named z
. That copy only lasts as long as the function. So once the function returns, it is no longer available to your program. So you can't have a valid pointer to it once the function returns: formally &z
is invalidated.
The same is true for the reference version int &p(int z) {return z}
.
As an exercise, see if you can figure out what would happen if z
was itself a reference: i.e. int &p(int& z) {return z}
. Then, a copy would not be taken. But do note that no professional would ever write a function like this.