C++ problematic code piece

后端 未结 3 1579
孤城傲影
孤城傲影 2021-01-23 15:03

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

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 16:02

    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.

提交回复
热议问题