如何初始化unique_ptr [英] How to initialize a unique_ptr

查看:751
本文介绍了如何初始化unique_ptr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的班级添加一个延迟初始化函数。我不太精通C ++。有人可以告诉我我如何实现它。

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))
{}

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

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?

推荐答案

#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;
}

这篇关于如何初始化unique_ptr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆