2017-04-09 66 views
0

我在努力正确初始化的std::unique_ptr's。矢量<unique_ptr>的初始化失败,出现复制错误

示例代码:

#include <iostream> 
#include <vector> 
#include <memory> 

class Base{ 
    public: 
     std::string getString() { return this->string; }; 
    protected: 
     std::string string; 
}; 
class Derived: public Base{ 
    public: 
     Derived(std::string bla){ 
      this->string = bla; 
    } 
}; 
class Collection{ 
    protected: 
     std::vector<std::unique_ptr<Base>> mappings; 
}; 
class DerivedCollection: public Collection{ 
    public: 
     DerivedCollection(std::string bla){ 
      std::vector<std::unique_ptr<Base>> maps; 
      maps.push_back(std::make_unique<Derived>(bla)); 
      //or this: (does not work aswell) 
      //maps.emplace_back(new Derived(bla)); 
      this->mappings = maps; 
     } 
}; 

int main(int argc, char** argv){ 
    DerivedCollection test = DerivedCollection("bla"); 
    return 0; 
} 

不知何故只定义mappings触发错误:

/usr/include/c++/6.3.1/bits/stl_construct.h:75:7: 
error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Base; _Dp = std::default_delete<Base>]’ 
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); } 

告诉我,我莫名其妙地设法从一个const的unique_ptr,这是自不起作用构造的unique_ptr unique_ptr不是可复制构建的。

不知何故,即使我对DerivedCollection构造函数中的所有内容进行评论,仍然会失败。

我的猜测是我需要一个适当的构造函数为Collection类。我不知道如何定义它。

任何想法?

- 马尔特

回答

4

maps是不可复制的,因为它的unique_ptr一个vector。它移入mappings解决了这个问题:

this->mappings = std::move(maps); 

live wandbox example


你的代码有其他一些问题:

  • 您应该使用成员初始化列表初始化数据成员而不是构造函数体

  • getString可能会返回const std::string&以避免副本。

  • Derived的构造函数可以将std::movebla写入数据成员。

  • test可以初始化如下:DerivedCollection test{"bla"}

  • new不应该被使用 - 使用make_unique来代替。

+0

或者,'std:swap(映射,映射)' – WhozCraig

+0

哇,这很简单。关于其他问题:这只是我在大约30秒内放在一起的一个简单例子,因此可以解释马虎的风格。此外,这个问题出现在我需要非平凡构造函数逻辑的上下文中,这就是为什么我没有使用启动列表。感谢您的提示,但! – Malte

相关问题