C++ 如何初始化unique_ptr

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32624077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:10:58  来源:igfitidea点击:

How to initialize a unique_ptr

c++classconstructorinitialization

提问by dotNET

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.

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

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:

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

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

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

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

采纳答案by Menos

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

回答by johnjohnlys

I think animal.reset(new Animal(file))is what you want.

我认为 Animal .reset(new Animal(file))是你想要的。

回答by asmmo

#include<iostream>
#include<memory>
#include<iostream>

class Amm{

    public:
    std::unique_ptr<double> myVar;
    explicit Amm(std::unique_ptr<double> ptr):myVar{ptr.release()}{}
};

int main(){
    Amm a(std::make_unique<double>(5));
    std::cout<<*a.myVar;

    return 0;

}