移动构造符签名 [英] Move constructor signature

查看:246
本文介绍了移动构造符签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考,它允许 const rvalue作为移动构造函数

From this reference, it allows a const rvalue as a move constructor

Type::Type( const Type&& other );

可移动对象如何可以 const

How can a movable object be const? Even if this was technically allowed, is there a case where such declaration would be useful?

推荐答案


即使这在技术上允许,如何可移动对象 const

这不是语言说的。语言说具有该签名的构造函数是一个移动构造函数,但这并不意味着参数被移动,它只是意味着构造函数满足移动构造函数的要求。移动构造函数不需要移动任何东西,如果参数 const ,它不能。

It can't, but that's not what the language says. The language says that a constructor with that signature is a "move constructor" but that doesn't mean the argument gets moved from, it just means the constructor meets the requirements of a "move constructor". A move constructor is not required to move anything, and if the argument is const it can't.


有这样的声明是有用的吗?

is there a case where such declaration would be useful?

是的,但不是很经常。如果你想防止另一个构造函数在一个const临时参数作为参数传递时通过重载解析来选择。

Yes, but not very often. It can be useful if you want to prevent another constructor being selected by overload resolution when a const temporary is passed as the argument.

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&&)

在此代码中,从 func()不会准确地匹配复制或移动构造函数的参数,因此将调用接受任何类型的模板构造函数。为了防止这种情况,你可以提供一个不同的重载取const常量,并且委托给拷贝构造函数:

In this code the temporary returned from func() will not match the copy or move constructors' parameters exactly, so will call the template constructor that accepts any type. To prevent this you could provide a different overload taking a const rvalue, and either delegate to the copy constructor:

Type(const Type&& t) : Type(t) { }

,将其定义为已删除:

Or if you want to prevent the code compiling, define it as deleted:

Type(const Type&& t) = delete;

请参阅 http://stackoverflow.com/a/4940642/981959 适用于使用常量值引用的标准中的示例。

See http://stackoverflow.com/a/4940642/981959 for examples from the standard that use a const rvalue reference.

这篇关于移动构造符签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆