C++ 如何在构造函数中初始化 std::unique_ptr?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19237206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to initialize std::unique_ptr in constructor?
提问by 0x499602D2
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.
有没有人知道为什么会发生这种情况?我尝试了很多不同的方法来让它工作,但无济于事。
回答by 0x499602D2
You need to initialize it through the member-initializer list:
您需要通过成员初始化列表来初始化它:
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.
您的示例是尝试调用operator ()
aunique_ptr
是不可能的。
Update: BTW, C++14 has std::make_unique
:
更新:顺便说一句,C++14 有std::make_unique
:
A::A(std::string filename) :
file(std::make_unique<std::ifstream>(filename));
{ }
回答by Jonathan Potter
You can do it like this:
你可以这样做:
A:A(std::string filename)
: file(new std::ifstream(filename.c_str())
{
}