c++ && 引用折叠

A& & 变成 A& A& && 变成 A& A&& & 变成 A& A&& && 变成 A&&

就是左值引用会传染,只有纯右值&& && = &&,沾上一个左值引用就变左值引用了

#include<bits/stdc++.h>
using namespace std;

class A
{
    public:
        A()
        {
            cout<<"default       "<<this<<endl;
        }

        A(const A& a)
        {
            cout<<"copy          "<<this<<endl;
        }

        A(A&& a)
        {
            cout<<"move          "<<this<<endl;
        }

        ~A()
        {
            cout<<"destructor    "<<this<<endl;
        }
};

A geta()
{
    return A();
}

A&& getb()
{
    return A();
}

void test_geta()
{
    cout<<"geta"<<endl;
    A a = geta();
    A&& b = geta();
}

void test_getb()
{
    cout<<endl;
    cout<<"getb"<<endl;
    A c = getb();
    A&& d = getb();
}

int main()
{   
    test_geta();
    test_getb();
    return 0;
}

答案:

geta
default       0x6ffdd6
default       0x6ffdd7
destructor    0x6ffdd7
destructor    0x6ffdd6

getb
default       0x6ffd8f
destructor    0x6ffd8f
move          0x6ffdd7
default       0x6ffd8f
destructor    0x6ffd8f
destructor    0x6ffdd7
文章目录