Returning const reference to local variable from a function

后端 未结 4 1431
夕颜
夕颜 2020-11-29 18:11

I have some questions on returning a reference to a local variable from a function:

class A {
public:
    A(int xx)
    : x(xx)
    {
        printf(\"A::A()         


        
4条回答
  •  暖寄归人
    2020-11-29 18:52

    Q1: Yes, this is a problem, see answer to Q2.

    Q2: 1 and 2 are undefined as they refer to local variables on the stack of getA1 and getA2. Those variables go out of scope and are no longer available and worse can be overwritten as the stack is constantly changing. getA3 works since a copy of the return value is created and returned to the caller.

    Q3: No such guarantee exists to see answer to Q2.

提交回复
热议问题