移动构造函数和初始化列表 [英] Move constructor and initialization list
问题描述
我想为某个类型实现移动构造函数(无复制构造函数),该类型需要是 boost :: unordered_map
中的值类型。让我们调用这个类型 Composite
。
I want to implement move constructors (no copy constructor) for a certain type that needs to be a value type in a boost::unordered_map
. Let's call this type Composite
.
以下签名:
Composite
has the following signature:
struct Base
{
Base(..stuff, no default ctor) : initialization list {}
Base(Base&& other) : initialization list {}
}
struct Composite
{
Base member;
Composite(..stuff, no default ctor) : member(...) {}
Composite(Composite&& other) : member(other.member) {} // <---- I want to make sure this invokes the move ctor of Base
}
这样写 boost :: unordered_map< Key,Composite>
不需要复制构造函数,只使用move构造函数。如果可能,我不想在 Composite
的move构造函数的初始化列表中使用 Base
。
I want to write this so boost::unordered_map< Key , Composite >
does not require the copy constructor, and just uses the move constructor. If possible, I don't want to use the copy constructor of Base
in the initialization list of move constructor of Composite
.
这是否可能?
推荐答案
说 member(std :: move(other.member))
。
你需要在 std :: move
中使用它,并且当你通过通用引用(即推导出模板类型&& code>),您需要在
std :: forward
中使用它。
As a golden rule, whenever you take something by rvalue reference, you need to use it inside std::move
, and whenever you take something by universal reference (i.e. deduced templated type with &&
), you need to use it inside std::forward
.
这篇关于移动构造函数和初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!