unique_ptr push_back和std :: list

时间:2016-11-26 18:25:08

标签: c++

我只是想知道如果可能的话,我如何能够将对象推回到具有unique_ptr的列表中。

我收到错误:

  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;
}

1 个答案:

答案 0 :(得分:0)

You should not use new for creating a new unique_ptr, but use std::make_unique (e.g., std::make_unique<Stimulation>("NAME1")).

I'd do

configuration.emplace_back("NAME1");

in order to not create an intermediate (see http://en.cppreference.com/w/cpp/container/vector/emplace_back; emplace_back creates a new object directly into the list, by calling the constructor).