Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 635
Mendes Avatar asked Jul 01 '15 23:07

Mendes


2 Answers

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));
like image 134
Galik Avatar answered Oct 19 '22 09:10

Galik


#include <memory>
...

int main()
{
    std::string testString{ "Testing 1...2....3" };
    auto test = std::make_unique<MyClass>( testString );
    return 0;
}
like image 32
davepmiller Avatar answered Oct 19 '22 08:10

davepmiller