【问题标题】:Difference between std::unordered_map < K, boost::ptr_deque < T > >'s operator[] (K const &) and emplacestd::unordered_map < K, boost::ptr_deque < T > > 的 operator[] (K const &) 和 emplace 的区别
【发布时间】:2016-08-24 18:40:07
【问题描述】:
#include <memory>
#include <unordered_map>
#include <vector>
#include <utility>
#include <boost/ptr_container/ptr_deque.hpp>

struct T
{
    T() = default;
    T(T const &) = delete;
    T & operator = (T const &) = delete;
    T(T &&) = default;
    T & operator = (T &&) = default;
};

using S = boost::ptr_deque < T >;

int main()
{
    std::unordered_map < uint32_t, S > testum;
    //  testum.emplace(1u, S());
    //  testum.insert(std::make_pair(1u, S()));
    testum[1].push_back(new T());
}

在上面的示例中,注释掉的行在尝试复制不可复制的 ptr_deque 的元素时无法编译。但是,push_back 表单有效。

我在想operator [] (K const &amp;) 只是return emplace(k, mapped_type()).first-&gt;secondreturn insert(value_type(k, mapped_type())).first-&gt;second,本质上是注释掉的语句

显然情况并非如此。 operator [] 是否在内部执行了一些 placement new 魔术?

或者ptr_deque有什么特别之处吗?

我正在使用 gcc-6.1 和 boost 1.59

【问题讨论】:

  • 也试试testum.emplace( std::piecewise_construct, std::make_tuple(1u), std::make_tuple() );
  • 谢谢。如果这是回复,我会投票并标记为答案

标签: c++11 boost unordered-map noncopyable boost-ptr-container


【解决方案1】:

根据http://en.cppreference.com/w/cpp/container/unordered_map/operator_at

2) 插入一个就地构造的 value_type 对象 std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple&lt;&gt;() 如果密钥不存在。

(我指的是Key&amp;&amp; 重载,因为在注释掉的行中,您使用右值作为operator[] 的参数。尽管在Key=int 的情况下差异非常小。 )

所以关于你的问题,operator[](Key&amp;&amp;) 大致相当于

return emplace(std::piecewise_construct,
               std::forward_as_tuple(std::move(k)),
               std::tuple<>()).first->second;

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 2014-12-14
    • 2020-03-03
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多