相关疑难解决方法(0)

C++ unique_ptr和map

我正在尝试使用C++ 0x unique_ptr,map如下所示:

// 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;
}
Run Code Online (Sandbox Code Playgroud)

但是GCC给了我以下错误(缩短了,我认为这是相关部分,请在您自己的C++编译器上测试):

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.我发现了非常相似的问题,看似相似,但是他们的解决方案对我不起作用.

matt@stanley:/media/data/src/c++0x-test$ gcc --version …

c++ gcc stl unique-ptr c++11

24
推荐指数
2
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1

gcc ×1

stl ×1

unique-ptr ×1