mercredi 1 juillet 2015

C++ How to create a std::unique_ptr from a class that takes parameters on constructor

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.

Aucun commentaire:

Enregistrer un commentaire