【问题标题】:Move constructor and initialization list移动构造函数和初始化列表
【发布时间】:2012-12-10 00:15:26
【问题描述】:

我想为需要在boost::unordered_map 中作为值类型的特定类型实现移动构造函数(无复制构造函数)。我们称这种类型为Composite

Composite 具有以下签名:

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&lt; Key , Composite &gt; 不需要复制构造函数,只使用移动构造函数。如果可能,我不想在Composite的移动构造函数的初始化列表中使用Base的复制构造函数。

这可能吗?

【问题讨论】:

    标签: c++ c++11 initialization unordered-map move-semantics


    【解决方案1】:

    member(std::move(other.member))

    作为黄金法则,无论何时通过右值引用获取某些内容,都需要在std::move 中使用它,而无论何时通过通用引用获取某些内容(即使用&amp;&amp; 推导出的模板类型),都需要使用它里面std::forward

    【讨论】:

    • +1 很好地使用了相对较新的术语通用参考
    • @MatthiasVallentin:这个词是 Scott Meyers 现场设计的。标准委员会现在更喜欢“转发参考”一词。
    • 我们已经快两年了,很高兴看到社区已经趋于稳定。
    猜你喜欢
    • 2014-11-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多