c++11 - C++ How to create a std::unique_ptr from a class that takes parameters on constructor -
i need create std::unique_ptr
class has constructor takes 1 parameter. can´t find references on how it. here code example cannot compile:
#include <iostream> #include <string> #include <sstream> #include <memory> class myclass { public: myclass(std::string name); virtual ~myclass(); private: std::string myname; }; myclass::myclass(std::string name) : myname(name) {} myclass::~myclass() {} class otherclass { public: otherclass(); virtual ~otherclass(); void myfunction(std::string data); std::unique_ptr<myclass> theclassptr; }; otherclass::otherclass() {} otherclass::~otherclass() {} void otherclass::myfunction(std::string data) { std::unique_ptr<myclass> test(data); <---------- problem here! theclassptr = std::move(test); } int main() { otherclass test; test.myfunction("this test"); }
the errors related way i´m initializing std::unique_ptr
, pointed out in code.
the original code , errors can found here.
thanks helping me solve that.
you can do:
std::unique_ptr<myclass> test(new myclass(data));
or if have c++14
auto test = std::make_unique<myclass>(data);
but:
in provided example there no need create temporary variable, can use reset
method of class member:
theclassptr.reset(new myclass(data));
Comments
Post a Comment