c++ - 此代码中的右值引用在哪里?
问题描述
我正在阅读这篇关于左值和右值的文章,我迷失在这一部分:
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。
解决方案
other
是变量的名称,因此是左值表达式。从左值表达式对数据成员的成员访问再次产生左值表达式,因此other._metadata
也是一个。
因此_metadata(other._metadata)
将调用复制构造函数,而不是移动构造函数。
std::move
左值表达式可以通过参数表达式中的调用变成右值(特别是 xvalue)表达式。std::move(other._metadata)
是一个右值表达式,调用_metadata(std::move(other._metadata))
将更喜欢移动构造函数重载,而不是复制构造函数。
推荐阅读
- arrays - 使用 PSRemotingJob 的动态菜单中的 IndexOf 错误
- sas - SAS导入杂乱数据
- python - 我们可以在 pandas 中自动检测特征类型为名义型还是有序型?
- c++ - C++ SDL2 无法加载任何文件
- python - 使用函数在列表中比较回文字符串
- python - 如何从频谱图图像中连接 MFCC 特征和纹理
- python - 保存音频文件的梅尔谱图而不显示它们的对应图
- javascript - React 应用程序“可以”条件中的 CASL 授权无效
- android - 单击时更改复选框背景?
- bootstrap-5 - 将引导程序 5 添加到角度 12