Returning const reference to local variable from a function

后端 未结 4 1437
夕颜
夕颜 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:44

    I think the main problem is that you are not returning temporaries at all, you should

    return A(5);
    

    rather than

    A a(5);
    return a;
    

    Otherwise you are returning local variable address, not temporary. And the temporary to const reference only works for temporaries.

    I think its explained here: temporary to const reference

提交回复
热议问题