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
891 views
in Technique[技术] by (71.8m points)

c++ - 如何初始化unique_ptr(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++.

(我不太精通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.

(我刚刚添加了一个无参数的构造函数和一个Init()函数。)

Here's the Init function I just added:

(这是我刚刚添加的Init函数:)

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

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

(我需要在那里写什么才能使其等同于构造函数在做什么?)

  ask by dotNET translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...