右值成员也是右值吗?

Are Rvalue members indeed Rvalues too?

本文关键字:成员      更新时间:2023-10-16

他们说右值的成员也是右值——这很有意义。因此,这要么是vc++特有的错误,要么是我对右值的理解中的错误。

拿这个玩具代码:

#include <vector>
#include <iostream>
using namespace std;
struct MyTypeInner
{
    MyTypeInner()   {};
    ~MyTypeInner()                     { cout << "mt2 dtor" << endl; }
    MyTypeInner(const MyTypeInner& other)  { cout << "mt2 copy ctor" << endl; }
    MyTypeInner(MyTypeInner&& other)       { cout << "mt2 move ctor" << endl; }
    const MyTypeInner& operator = (const MyTypeInner& other)
    {
        cout << "mt2 copy =" << endl;       return *this;
    }
    const MyTypeInner& operator = (MyTypeInner&& other)
    {
        cout << "mt2 move =" << endl;       return *this;
    }
};
struct MyTypeOuter
{
    MyTypeInner mt2;
    MyTypeOuter()   {};
    ~MyTypeOuter()                     { cout << "mt1 dtor" << endl; }
    MyTypeOuter(const MyTypeOuter& other)  { cout << "mt1 copy ctor" << endl;  mt2 = other.mt2; }
    MyTypeOuter(MyTypeOuter&& other)       { cout << "mt1 move ctor" << endl;  mt2 = other.mt2; }
    const MyTypeOuter& operator = (const MyTypeOuter& other)    
    {
        cout << "mt1 copy =" << endl;       mt2 = other.mt2;   return *this;
    }
    const MyTypeOuter& operator = (MyTypeOuter&& other)
    {
        cout << "mt1 move =" << endl;   mt2 = other.mt2;    return *this;
    }
};
MyTypeOuter func()   {  MyTypeOuter mt; return mt; }
int _tmain()
{
    MyTypeOuter mt = func();
    return 0;
}

这段代码输出:

mt2 copy =

mt1井底扭矩

是井底扭矩

也就是说,MyTypeOuter的move函数调用MyTypeInner的copy,而不是move。如果我将代码修改为:
MyTypeOuter(MyTypeOuter&& other)       
{ cout << "mt1 move ctor" << endl;  mt2 = std::move(other.mt2); }

输出如预期:

mt2 move =

mt1井底扭矩

是井底扭矩

似乎vc++(2010和2013)不尊重这部分标准。还是我错过了什么?

rvalue的成员是否为rvalue不是这里的问题,因为您正在处理赋值操作符中的左值。

在这个move赋值操作符中,

const MyTypeOuter& operator = (MyTypeOuter&& other)
{
    cout << "mt1 move =" << endl;
    mt2 = other.mt2;
    return *this;
}

other是一个lvalue(因为它有一个名字),通过扩展other.mt2也是。当您说mt2 = other.mt2时,您只能调用标准赋值操作符。

为了调用move构造函数,您需要使other.mt2 看起来像右值,这就是std::move所实现的:

const MyTypeOuter& operator = (MyTypeOuter&& other)
{
    cout << "mt1 move =" << endl;   
    mt2 = std::move(other.mt2);
    return *this;
}