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 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));
{ }
关于c++ - 如何在构造函数中初始化 std::unique_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19237206/