I need to create a std::unique_ptr
from a class that has a constructor that takes one parameter. I can´t find references on how to do it. Here is the code example that 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 is a test");
}
The errors are related to the way I´m initializing the std::unique_ptr
, pointed out in my code.
The original code and the errors can be found here.
Thanks for helping me to solve that.
You can do:
std::unique_ptr<MyClass> test(new MyClass(data));
Or if you have C++14
auto test = std::make_unique<MyClass>(data);
But:
In the provided example there is no need to create a temporary variable, you can just use the reset
method of the class member:
theClassPtr.reset(new MyClass(data));
#include <memory>
...
int main()
{
std::string testString{ "Testing 1...2....3" };
auto test = std::make_unique<MyClass>( testString );
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With