C ++ unique_ptr和map [英] C++ unique_ptr and map

查看:977
本文介绍了C ++ unique_ptr和map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 C ++ 0x unique_ptr class 里面< a href =http://en.cppreference.com/w/cpp/container/map =nofollow> map 如下:

I'm trying to use the C++0x unique_ptr class inside a map like so:

// compile with `g++ main.cpp -std=gnu++0x`

#include <string.h>    
#include <map>
#include <memory>

using namespace std;

struct Foo {
    char *str;    
    Foo(char const *str_): str(strdup(str_)) {}
};

int main(void) {
    typedef std::map<int, unique_ptr<Foo>> Bar;
    Bar bar;
    auto a = bar.insert(Bar::value_type(1, new Foo("one")));
    return 0;
}

但是GCC给了我以下错误部分,请测试你自己的C ++编译器):

However GCC gives me the following error (shortened, I think this is the relevant part, please test on your own C++ compiler):


main.cpp:19:   instantiated from here
/usr/include/c++/4.4/bits/unique_ptr.h:214: error: deleted function ‘std::unique_ptr::unique_ptr(const std::unique_ptr&) [with _Tp = Foo, _Tp_Deleter = std::default_delete]’
/usr/include/c++/4.4/bits/stl_pair.h:68: error: used here

我真的不知道我做错了,这对MSVC工作。我发现非常类似类似的问题,但是他们的解决方案不为我工作。

I'm really not sure what I've done wrong, this works on MSVC. I have found very similar questions, that seem alike, however their solutions do not work for me.


matt@stanley:/media/data/src/c++0x-test$ gcc --version
gcc-4.4.real (Ubuntu 4.4.3-4ubuntu5) 4.4.3


推荐答案

我不相信在 map :: insert 中可以正确使用 unique_ptr 以下是GCC错误:

I don't believe it's possible to correctly use unique_ptr in a map::insert yet. Here's the GCC bug for it:

Bug 44436 - [C ++ 0x]在关联和无序容器中实现插入(&&) emplace * / a>

它似乎可能是修正为GCC 4.6 ,但它不会从SVN上建立在Ubuntu 10.04.1版本上的确认。

It looks like it may be fixed for GCC 4.6, but it won't build from SVN on vanilla Ubuntu 10.04.1 to confirm.

这是不工作的GCC svn r165422(4.6.0)。

This is not working as of GCC svn r165422 (4.6.0).

这篇关于C ++ unique_ptr和map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆