Norman Norman - 11 months ago 55
C++ Question

C++ problematic code piece

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 these snippets of code problematic?

int& p(int z) { return z; }
int* h(int z) { return &z; }


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.