我需要从具有带一个参数的构造函数的类创建一个std::unique_ptr
。我找不到有关如何操作的参考资料。这里是不能编译的代码示例:C++如何从构造函数上需要参数的类创建std :: unique_ptr
#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");
}
的错误的方式有关I'm初始化std::unique_ptr
,在我的代码中指出。
原始码和错误可以在here找到。
感谢您帮助我解决这个问题。
使用'std :: make_unique',它将参数转发给构造函数。 –
我试过了,但是我不能编译它...... seens认为std :: make_unique在C++ 11上不受支持...... – Mendes
你能显示没有用的代码吗? –