首页 > 解决方案 > 此代码中的右值引用在哪里?

问题描述

我正在阅读这篇关于左值和右值的文章,我迷失在这一部分:

class MetaData
{
public:
    MetaData (int size, const std::string& name)
        : _name( name )
        , _size( size )
    {}

    // copy constructor
    MetaData (const MetaData& other)
        : _name( other._name )
        , _size( other._size )
    {}

    // move constructor
    MetaData (MetaData&& other)
        : _name( other._name )
        , _size( other._size )
    {}

    std::string getName () const { return _name; }
    int getSize () const { return _size; }
    private:
    std::string _name;
    int _size;
};

和:

class ArrayWrapper
{
public:
    // default constructor produces a moderately sized array
    ArrayWrapper ()
        : _p_vals( new int[ 64 ] )
        , _metadata( 64, "ArrayWrapper" )
    {}

    ArrayWrapper (int n)
        : _p_vals( new int[ n ] )
        , _metadata( n, "ArrayWrapper" )
    {}

    // move constructor
    ArrayWrapper (ArrayWrapper&& other)
        : _p_vals( other._p_vals  )
        , _metadata( other._metadata )
    {
        other._p_vals = NULL;
    }

    // copy constructor
    ArrayWrapper (const ArrayWrapper& other)
        : _p_vals( new int[ other._metadata.getSize() ] )
        , _metadata( other._metadata )
    {
        for ( int i = 0; i < _metadata.getSize(); ++i )
        {
            _p_vals[ i ] = other._p_vals[ i ];
        }
    }
    ~ArrayWrapper ()
    {
        delete [] _p_vals;
    }
private:
    int *_p_vals;
    MetaData _metadata;
};

作者继续解释:

...The reason is simple: the value of other in the move constructor--it's an rvalue reference.

我想他指的是 ArrayWrapper 的移动构造函数 where:_metadata( other._metadata )被看到。这对我来说似乎是左值,而不是右值引用。

It's an lvalue, and so the copy constructor is called, not the move constructor.

他是想说_metadata( other._metadata )导致复制构造函数Metadata被调用吗?

有人可以帮忙吗?TIA。

标签: c++rvalue-referencervalue

解决方案


other是变量的名称,因此是左值表达式。从左值表达式对数据成员的成员访问再次产生左值表达式,因此other._metadata也是一个。

因此_metadata(other._metadata)将调用复制构造函数,而不是移动构造函数。

std::move左值表达式可以通过参数表达式中的调用变成右值(特别是 xvalue)表达式。std::move(other._metadata)是一个右值表达式,调用_metadata(std::move(other._metadata))将更喜欢移动构造函数重载,而不是复制构造函数。


推荐阅读