【问题标题】:How to initialize std::unique_ptr in constructor?如何在构造函数中初始化 std::unique_ptr?
【发布时间】:2013-10-14 18:09:18
【问题描述】:

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

有没有人知道为什么会发生这种情况?我已经尝试了许多不同的方法来让它工作,但都无济于事。

【问题讨论】:

    标签: c++ smart-pointers ifstream unique-ptr


    【解决方案1】:

    你可以这样做:

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

    【讨论】:

      【解决方案2】:

      你需要通过member-initializer list来初始化它

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

      【讨论】:

      • 如果您需要事先检查构造函数,也可以调用file 上的reset() 函数来分配unique_ptr
      • 您不一定必须使用成员初始化器列表。不过,它更可取。
      • @JohnJohn,如果你使用 Pimpl,你应该使用成员初始化器列表,因为你的 std::unique_ptr 是 const。
      • 关于file(new ...)file(std::make_unique...) 的使用:有什么理由更喜欢其中一个吗?
      猜你喜欢
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2016-05-07
      • 2020-04-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 2022-01-22
      相关资源
      最近更新 更多