Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - How to initialize a unique_ptr

I'm trying to add a lazy-initialization function to my class. I'm not very proficient with C++. Can someone please tell me how I achieve it.

My class has a private member defined as:

std::unique_ptr<Animal> animal;

Here's the original constructor that takes one parameter:

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

I just added a parameter-less constructor and an Init() function. Here's the Init function I just added:

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

What do I need to write there to make it equivalent to what constructor is doing?

question from:https://stackoverflow.com/questions/32624077/how-to-initialize-a-unique-ptr

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

1 Reply

0 votes
by (71.8m points)
#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...