简体   繁体   English

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

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

A.hpp: A.hpp:

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

A.cpp: 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. 我已经尝试了很多不同的方法让它工作,但无济于事。

You need to initialize it through the member-initializer list : 您需要通过member-initializer列表初始化它:

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. 您的示例是尝试在unique_ptr上调用operator () ,这是不可能的。

Update: BTW, C++14 has std::make_unique : 更新:BTW,C ++ 14有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())
{
}

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

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