Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

c++ - 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()));
}

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.

question from:https://stackoverflow.com/questions/19237206/how-to-initialize-stdunique-ptr-in-constructor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

Update: BTW, C++14 has std::make_unique:

A::A(std::string filename) :
    file(std::make_unique<std::ifstream>(filename));
{ }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...