![](/img/trans.png)
[英]How do I initialize a std::unique_ptr with a deleter in a constructor?
[英]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.