尝试将unique_ptr放入映射时编译错误

时间:2016-01-13 15:19:48

标签: c++ c++11

我有一个Load-Method,用于构建我的unique_ptr(稍后将会有多个)以及一个将这些unique_ptr添加到我的无序地图的方法。但是代码没有编译,我想它与范围界定有关...

以下是代码:

#include <unordered_map>
#include <memory>

class MyClass
{
    public:
        std::string Name;
};

using Map = std::unordered_map<std::string,std::unique_ptr<MyClass>>;


class MyContainer
{
    private:
        Map myMap;
        void AddItem(std::unique_ptr<MyClass> item)
        {
            myMap.emplace("test", item);
        }
    public:
        void LoadItems()
        {
            //Read a file ... do something before etc..
            std::unique_ptr<MyClass> someItem(new MyClass);
            someItem->Name = "FooBar";
            AddItem(someItem);
        }
};

这是g ++错误消息之一:

  

错误:使用已删除的函数&#39; std :: unique_ptr&lt; _Tp,   _Dp&gt; :: unique_ptr(const std :: unique_ptr&lt; _Tp,_Dp&gt;&amp;)[with _Tp = MyClass; _Dp = std :: default_delete]&#39;

让这项工作最好的方法是什么?我尝试更改AddItem方法的签名,如下所示:

void AddItem(std::unique_ptr<MyClass>& item) //takes a reference now...

这导致了一个真正神秘的错误信息:

  

实例化&#39; constexpr std :: pair&lt; _T1,_T2&gt; :: pair(_U1&amp;&amp;,const   _T2&amp;)[with _U1 = const char(&amp;)[5]; =无效_T1 = const std :: basic_string; _T2 = std :: unique_ptr]&#39;:e:\ devtools \ winbuilds \ include \ c ++ \ 4.8.3 \ bits \ hashtable_policy.h:177:55:   需要来自&#39; std :: __ detail :: _ ...

我建议在这里动态尝试这段代码,以查看错误消息: http://cpp.sh/

2 个答案:

答案 0 :(得分:11)

您无法复制NSString *script = @"document.getElementsByTagName('body')[0].innerHTML.length"; NSString *length = [self.webView stringByEvaluatingJavaScriptFromString:script]; if (length.integerValue > 0) { NSLog(@"not empty"); } ,因为它不会是唯一的。您必须移动它 - unique_ptrAddItem(std::move(someItem));

答案 1 :(得分:2)

您正在尝试复制不允许的 unique_ptr (该构造函数已被删除,因为gcc在错误中说明)。而不是你可以尝试使用 std :: move

#include <unordered_map>
#include <memory>
#include <utility>

class MyClass
{
    public:
         std::string Name;
};

using Map = std::unordered_map<std::string,std::unique_ptr<MyClass>>;


class MyContainer
{
    private:
        Map myMap;
        void AddItem(std::unique_ptr<MyClass> item)
        {
            myMap.emplace("test", std::move(item));
        }
    public:
        void LoadItems()
        {
            //Read a file ... do something before etc..
            std::unique_ptr<MyClass> someItem(new MyClass);
            someItem->Name = "FooBar";
            AddItem(std::move(someItem));
        }
};

请注意,之后不要使用移动的对象。

您可以考虑改用 shared_ptr

相关问题