How to initialize a unique_ptr

天大地大妈咪最大 提交于 2020-01-31 06:16:13

问题


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?


回答1:


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



回答2:


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




回答3:


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

}


来源:https://stackoverflow.com/questions/32624077/how-to-initialize-a-unique-ptr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!