2016-08-24 49 views
0
#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窗体的工作。差分<K,升压:: ptr_deque < T >>的操作符[](K常量&)和布设

我在想,operator [] (K const &)简直是return emplace(k, mapped_type()).first->secondreturn insert(value_type(k, mapped_type())).first->second,这在本质上是注释语句

显然事实并非如此。 operator []在内部执行一些placement new魔法吗?

或者有什么特别的关于ptr_deque

我使用GCC-6.1 &升压1.59

+0

尝试也'testum.emplace(STD :: piecewise_construct,性病:: make_tuple(1U)的std :: make_tuple());' – aschepler

+0

谢谢。如果这是一个答复,我会投票并标记为答案 – zrb

回答

2

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

2)插入,如果键不存在就地从 std::piecewise_construct, std::forward_as_tuple(std::move(key)), std::tuple<>() 构造的value_type对象。

(我指的是Key&&超载,因为在注释掉线,您使用的是右值作为参数传递给operator[],虽然在Key=int的情况下,差异是非常微不足道的。)

因此,在参考你的问题,operator[](Key&&)大致相当于

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