2016-11-26 217 views
-1

我只是想知道如何能夠將對象推回到unique_ptr列表中,如果可能的話。unique_ptr push_back和std :: list

我收到的錯誤:

error: 
    no matching constructor for initialization of 
    'std::__1::unique_ptr<tester::Stimulation, 
    std::__1::default_delete<tester::Stimulation> >' 
      ::new ((void*)__p) _Tp(__a0); 

我的代碼如下:

#include <iostream> 
#include <list> 

namespace tester 
{ 
    class Stimulation 
    { 
    std::string name; 

    public: 
    Stimulation(std::string n) : name(n) {} 
    std::string getName() const {return name;} 
    }; 
} 

using namespace tester; 


int main(int argc, char const *argv[]) 
{ 
    std::list< std::unique_ptr<tester::Stimulation*> > configuration; 
    //std::list< std::unique_ptr<tester::Stimulation> >::iterator i = configuration.begin(); 

    configuration.push_back(std::unique_ptr<tester::Stimulation>(new Stimulation("NAME1"))); 


    return 0; 
} 
+0

你的代碼有什麼問題? – wasthishelpful

+0

我不確定,但你的代碼對我來說確實很好。請發佈相關的錯誤消息。 – Rakete1111

+0

已更新:提供了錯誤 –

回答

0

創建新的unique_ptr你不應該使用new,但使用std::make_unique(例如,std::make_unique<Stimulation>("NAME1"))。

我做

configuration.emplace_back("NAME1"); 

,以不產生中間(見http://en.cppreference.com/w/cpp/container/vector/emplace_back; emplace_back直接創建一個新對象到列表中,通過調用構造函數)。

+0

所以只需使用emplace_back,而不是在列表中聲明唯一的ptr? –

+0

你仍然可以使用push_back,但是你需要使用std :: make_unique。 'emplace_back'直接調用'unique_ptr'的構造函數。 – MrTux

+0

'std :: __ 1 :: list >, std: :__ 1 :: allocator >>>' –

相關問題