2015-09-17 32 views
9

私は自分のクラスに遅延初期化関数を追加しようとしています。私はC++に堪能ではありません。誰かが私がそれを達成する方法を教えてもらえますか?unique_ptrを初期化する方法

私のクラスのように定義されたプライベートメンバーました:ここに1つのパラメータを取り、元のコンストラクタは

std::unique_ptr<Animal> animal; 

です:

MyClass::MyClass(string file) : 
animal(new Animal(file)) 
{} 

私はちょうどパラメータなしのコンストラクタとinit()関数を追加しました。ここに私が追加したInit関数があります:

void MyClass::Init(string file) 
{ 
    this->animal = ???; 
} 

何がコンストラクタがやっていることと同等にするためにそこに書き込む必要がありますか?

+2

メンバー初期化子リストで['std :: make_unique (file)'](http://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique)を使用してください。 –

+0

簡単な例:http://en.cppreference.com/w/cpp/memory/unique_ptr – cbinder

+0

'???'の場合、 'std :: make_unique (file)'を使うことができます。 –

答えて

7
#include <memory> 
#include <algorithm> 
#include <iostream> 
#include <cstdio> 

class A 
{ 
public : 
    int a; 
    A(int a) 
    { 
     this->a=a; 

    } 
}; 
class B 
{ 
public : 
    std::unique_ptr<A> animal; 
    void Init(int a) 
    { 
     this->animal=std::unique_ptr<A>(new A(a)); 
    } 
    void show() 
    { 
     std::cout<<animal->a; 
    } 
}; 

int main() 
{ 
    B *b=new B(); 
    b->Init(10); 
    b->show(); 
    return 0; 
} 
+1

これは、他の友人が提案した 'make_unique'と同じですか? – dotNET

+5

おそらく 'this-> animal = std :: make_unique (a); –

関連する問題