C++ 将std::unique\u ptr插入boost:ptr\u映射

C++ 将std::unique\u ptr插入boost:ptr\u映射,c++,c++11,boost,c++14,C++,C++11,Boost,C++14,我正在将一些旧代码移到c++14,它使用了不推荐使用的auto_ptr,这与boost:ptr_map配合得很好,您可以: auto_ptr<Foo> foo(new Foo); boost:map_ptr<int, Foo> m; m.insert(5, foo); auto_ptr foo(新foo); boost:map_ptr m; m、 插入(5,foo); 现在,用unique_ptr替换auto_ptr,它不会编译: unique_ptr<Foo&

我正在将一些旧代码移到c++14,它使用了不推荐使用的auto_ptr,这与boost:ptr_map配合得很好,您可以:

auto_ptr<Foo> foo(new Foo);
boost:map_ptr<int, Foo> m;
m.insert(5, foo);
auto_ptr foo(新foo);
boost:map_ptr m;
m、 插入(5,foo);
现在,用unique_ptr替换auto_ptr,它不会编译:

unique_ptr<Foo> foo(new Foo);
boost:map_ptr<int, Foo> m;
m.insert(5, foo);            // Does not compile
m.insert(5, move(foo));      // Does not compile either,
                             // this should be the right thing to do
m.insert(5, move.release()); // Does compile, but isn't exception safe
unique_ptr<Foo> foo(new Foo);
void *ptr = foo;
unique_ptr foo(新foo);
boost:map_ptr m;
m、 插入(5,foo);//不编译
m、 插入(5,移动(foo));//也不编译,,
//这应该是正确的做法
m、 插入(5,move.release());//编译,但不是异常安全的
map_ptr API还不是最新的吗

根据响应进行编辑,在我的例子中,使用唯一的映射不是一个好的选择,因为它需要重写大量的代码。我真的很想让它与map_ptr一起工作,我正在处理一些旧代码,我希望进行最小的更改

map_ptr API还不是最新的吗

不,你只是用错了

自以下日期起:

ptr_映射是一个指针容器,它使用底层std::map来存储指针

请注意,这不会编译:

unique_ptr<Foo> foo(new Foo);
boost:map_ptr<int, Foo> m;
m.insert(5, foo);            // Does not compile
m.insert(5, move(foo));      // Does not compile either,
                             // this should be the right thing to do
m.insert(5, move.release()); // Does compile, but isn't exception safe
unique_ptr<Foo> foo(new Foo);
void *ptr = foo;
另一方面,它编译:

unique_ptr<Foo> foo(new Foo);
Foo *bar = foo.realease();
void *ptr = bar;
因此,你不能期望第一个案例起作用,实际上它不起作用


也就是说,现在我宁愿使用标准模板库中的int和
std::unique_ptr
映射,而不使用
boost::ptr_map
,正如对问题的评论所建议的那样。
类似于以下的方法应该可以工作:

std::map<int, std::unique_ptr<Foo>>
std::map

请注意,
std::map
std::unordered_map
更合适,如果您想要更接近
boost::ptr_map
的工作方式,如上所述,其底层数据结构是
std::map
而不是
std::unordered_map

我认为在C++14中您想要的是:

std::unordered_map<int, std::unique_ptr<Foo>> x;
x.emplace(5, std::make_unique<Foo>());
std::无序地图x;
x、 安放(5,std::make_unique());
您不再需要那些旧的boost\u ptr容器了,它们基本上是解决办法,因为它们缺少一个可在容器中安全处理的零开销指针(即
unique\u ptr
)。

您可以使用

std::unordered_map<int, std::unique_ptr<Foo>> x;
x.emplace(5, std::make_unique<Foo>());
std::无序地图x;
x、 安放(5,std::make_unique());

这是一个C++14特性。不需要旧的增压容器!!!:)

什么是boost ptr_图?你确定在C++14中仍然需要它吗?我不认为你会这么做,那些旧的指针容器是为了解决一个事实,即auto_ptr实际上不能由容器进行一般处理。为什么不直接使用
std::map
,我应该提到这对我来说不是一个选项,因为这不是ptr_地图的替代品,就像unique_ptr主要是针对我所拥有的特定代码的auto_ptr一样。我必须说,ptr_地图比独特的ptr地图使用起来更好一点。