为什么这会导致C2102:'&'需要l值 [英] Why this is causing C2102: '&' requires l-value

查看:300
本文介绍了为什么这会导致C2102:'&'需要l值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么以下代码方式(已经注释掉)会导致

C2102:'&'需要左值

I was wondering, why the following way of code (Already commented out) will cause
C2102: '&' requires l-value

是否有更好的方法来避免使用 tmp 变量?

Is there a better way to avoid using tmp variable?

class a {
private:
    int *dummy;
public:
    int* get_dummy() const {
        return dummy;
    }
};

int main()
{
    a aa;

    // error C2102: '&' requires l-value
    //int** me = &(aa.get_dummy());

    // OK!
    int *tmp = aa.get_dummy();
    int** me = &(tmp);
}


推荐答案

因为 a :: get_dummy()返回未命名的临时对象(int指针)。

函数返回的对象位于堆栈框架的顶部,并且获取其地址没有意义,因为在表达式结束后它可能无效。

Because a::get_dummy() returns a unnamed temporary object (int pointer).
Object returned by function sit ontop of the stack frame and it is meaningless to get its address since it might be invalid after expression ends.

这篇关于为什么这会导致C2102:'&'需要l值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆