如何在构造函数中初始化std::unique_ptr?

46

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

我得到的错误是被抛出的:

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

有人知道为什么会发生这种情况吗?我尝试了许多不同的方法来解决这个问题,但都没有成功。


这与编程有关。 - mrpandey
2个回答

57

您需要通过成员初始化列表来初始化它:

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

你的示例尝试在 unique_ptr 上调用 operator (),这是不可能的。

更新:顺便提一下,C++14有 std::make_unique

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

5
如果你需要在构造函数之前进行一些检查,可以将unique_ptr分配给file,或者在file上调用reset()函数。 - gigaplex
您不一定需要使用成员初始化列表,但最好还是这样做。 - JohnJohn
1
@JohnJohn,如果您正在使用Pimpl,则应使用成员初始化列表,因为您的std :: unique_ptr是const。 - csguth
1
关于使用 file(new ...)file(std::make_unique...):有没有更倾向于其中一种的原因? - Dirk Herrmann

6
你可以这样做:
A:A(std::string filename)
    : file(new std::ifstream(filename.c_str())
{
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接