Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize std::unique_ptr in constructor?

People also ask

What is std :: unique_ptr?

std::unique_ptr is a smart pointer that owns and manages another object through a pointer and disposes of that object when the unique_ptr goes out of scope. The object is disposed of, using the associated deleter when either of the following happens: the managing unique_ptr object is destroyed.

Do I need to delete unique_ptr?

An explicit delete for a unique_ptr would be reset() . But do remember that unique_ptr are there so that you don't have to manage directly the memory they hold. That is, you should know that a unique_ptr will safely delete its underlying raw pointer once it goes out of scope.


You need to initialize it through the member-initializer list:

A::A(std::string filename) :
    file(new std::ifstream(filename));
{ }

Your example was an attempt to call operator () on a unique_ptr which is not possible.

Update: BTW, C++14 has std::make_unique:

A::A(std::string filename) :
    file(std::make_unique<std::ifstream>(filename));
{ }

You can do it like this:

A:A(std::string filename)
    : file(new std::ifstream(filename.c_str())
{
}