C++ 当使用临时对象访问时,为什么引用类型是左值?

C++ 当使用临时对象访问时,为什么引用类型是左值?,c++,c++11,C++,C++11,为什么给使用临时对象访问的引用变量赋值有效,但对非引用类型无效 class a { public: int m; int &n; a():m(2),n(m) { cout<< "A's constructor"<<endl; } }; int main() { // a().m = 6; // this gives an error that

为什么给使用临时对象访问的引用变量赋值有效,但对非引用类型无效

class a
{
    public:
        int m;
        int &n;
        a():m(2),n(m)
        {
            cout<< "A's constructor"<<endl;
        }
};

int main()
{
    // a().m = 6; // this gives an error that a temporary object is being used 
                  // as an lvalue
    a().n = 20;   // But this line works

    return 0;
}
a类
{
公众:
int m;
国际及北;
a():m(2),n(m)
{
库特
因为
n
是一个左值引用类型,所以编译器不知道
n
是实现中对
m
的引用。它假定
n
是一个有效的左值引用,因此接受该行

理论上,当您分配给
a().n
时,您可以分配给一个独立于
a()
生命周期的变量。编译器无法评估这一点,如果不接受这一行,将妨碍程序员。想象下面的用例:

// Global variable.
int gv;

class a
{
    public:
        int m;
        int &n;
        a():m(2), n(gv)  // n is a reference to the global variable.
        {
            cout<< "A's constructor"<<endl;
        }
};

int main()
{
    a().n = 20;   // Changes gv. It is a valid operation.
    return 0;
}
//全局变量。
国际旅行社;
甲级
{
公众:
int m;
国际及北;
a():m(2),n(gv)//n是对全局变量的引用。
{
CUT< P>但<代码> >():N</代码>真的是临时的吗?请考虑此代码:

class a
{
    public:
        int m;
        int &n;
        a():m(2),n(m)
        {
            cout<< "A's constructor"<<endl;
        }

        a(int& _n):m(2),n(_n)
        {
            cout<< "A's constructor"<<endl;
        }
};

int main()
{
    a().n = 20;   // (1)

    int n = 0;
    a(n).n        // (2)

    return 0;
}
在您的代码中,
a()
是prvalue或类型
a
。它的所有值成员也是。这就是为什么
a().m
不起作用。
m
是prvalue

但是,
a()
class a
{
    public:
        int m;
        int &n;
        a():m(2),n(m)
        {
            cout<< "A's constructor"<<endl;
        }

        a(int& _n):m(2),n(_n)
        {
            cout<< "A's constructor"<<endl;
        }
};

int main()
{
    a().n = 20;   // (1)

    int n = 0;
    a(n).n        // (2)

    return 0;
}
9 = 8; // nope