2013-10-08 17 views
25

A.hpp:コンストラクタでstd :: unique_ptrを初期化するには?

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

誰もこれが発生している理由として、任意の洞察力を持っています?私はこれを動作させるには多くの異なる方法を試しましたが、役に立たないものです。

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

答えて

29

あなたはメンバー初期化子リストを通してそれを初期化する必要があります:あなたはこのようにそれを行うことができます

+2

あなたは、コンストラクタで、いくつかのチェックを行う必要がある場合代わりに 'unique_ptr'を割り当てることがfile''の 'リセット()'関数を呼び出します予め。 – gigaplex

+0

必ずしもメンバー初期化リストを使用する必要はありません。しかし、より好ましい。 – JohnJohn

+1

@JohnJohn、Pimplを使用している場合は、std :: unique_ptrがconstなので、member-initializerリストを使用する必要があります。 – csguth

4

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

あなたの例では、unique_ptroperator()を呼び出そうとしましたこれは不可能です。

更新:ところで、C++ 14がstd::make_uniqueがあります

A::A(std::string filename) : 
    file(std::make_unique<std::ifstream>(filename)); 
{ } 
関連する問題