2017-04-09 29 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