繁体   English   中英

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

[英]How to initialize std::unique_ptr in constructor?

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*)’

有没有人知道为什么会这样? 我已经尝试了很多不同的方法让它工作,但无济于事。

您需要通过member-initializer列表初始化它:

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

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

更新:BTW,C ++ 14有std::make_unique

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

你可以这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM