【问题标题】:How to initialize a unique_ptr如何初始化一个unique_ptr
【发布时间】:2015-09-17 06:46:47
【问题描述】:

我正在尝试向我的班级添加延迟初始化函数。我对C++不是很精通。谁能告诉我我是如何实现的。

我的班级有一个私有成员定义为:

std::unique_ptr<Animal> animal;

这是带有一个参数的原始构造函数:

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

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

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

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

【问题讨论】:

标签: c++ class constructor initialization


【解决方案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;
}

【讨论】:

  • 这和其他朋友建议的make_unique一样吗?
  • 更好的可能是this-&gt;animal = std::make_unique&lt;A&gt;(a);
  • 是一样的。我认为我的更蹩脚
  • @DavidSchwartz:当我写 animal = std::make_unique&lt;Animal&gt;(Animal(file)); 时,它告诉我“试图引用已删除的函数”。
  • @DavidSchwartz:天啊。一下子,一切都变得清晰起来。感觉好笨混淆是由于我的参数被命名为file,而不是a。 Menos 示例实际上使用了a。不管怎样,谢谢你对我的包容。我现在已经切换到这种语法了。
【解决方案2】:

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

http://en.cppreference.com/w/cpp/memory/unique_ptr/reset

【讨论】:

  • 比其他变体短得多并且可以工作。谢谢!
【解决方案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;

}

【讨论】:

    猜你喜欢
    • 2020-04-17
    • 2013-06-15
    • 2020-04-16
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多