How to initialize std::unique_ptr in constructor?

user1529891 picture user1529891 · Oct 8, 2013 · Viewed 38.9k times · Source

A.hpp:

class A {
  private:
   std::unique_ptr<std::ifstream> file;
  public:
   A(std::string filename);
};

A.cpp:

A::A(std::string filename) {
  this->file(new std::ifstream(filename.c_str()));
}

The error that I get is thrown:

A.cpp:7:43: error: no match for call to ‘(std::unique_ptr<std::basic_ifstream<char> >) (std::ifstream*)’

Does anyone have any insight as to why this is occurring? I've tried many different ways to get this to work but to no avail.

Answer

0x499602D2 picture 0x499602D2 · Oct 8, 2013

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));
{ }