bal*_*lki 7 c++ move-constructor c++11
从该引用中,它允许const
rvalue作为移动构造函数
Type::Type( const Type&& other );
Run Code Online (Sandbox Code Playgroud)
可移动物体怎么样const
?即使这在技术上是允许的,是否存在这样的声明有用的情况?
可移动物体怎么样
const
?
它不能,但这不是语言所说的.该语言表示具有该签名的构造函数是"移动构造函数",但这并不意味着参数被移动,它只是意味着构造函数满足"移动构造函数"的要求.移动构造函数不需要移动任何东西,如果参数是const
它不能.
是否有这种声明有用的情况?
是的,但不是经常.如果要在const临时作为参数传递时阻止通过重载决策选择另一个构造函数,这将非常有用.
struct Type
{
template<typename T>
Type(T&&); // accepts anything
Type(const Type&) = default;
Type(Type&&) = default;
};
typedef const Type CType;
CType func();
Type t( func() ); // calls Type(T&&)
Run Code Online (Sandbox Code Playgroud)
在此代码中,返回的临时值func()
与复制或移动构造函数的参数不完全匹配,因此将调用接受任何类型的模板构造函数.为了防止这种情况,您可以使用const rvalue提供不同的重载,并委托给复制构造函数:
Type(const Type&& t) : Type(t) { }
Run Code Online (Sandbox Code Playgroud)
或者,如果要阻止代码编译,请将其定义为已删除:
Type(const Type&& t) = delete;
Run Code Online (Sandbox Code Playgroud)
有关使用const右值引用的标准中的示例,请参阅/sf/answers/345844971/.
归档时间: |
|
查看次数: |
1006 次 |
最近记录: |