【问题标题】:How can I use Unique_ptrs with an class object having std::function as argument in the constructor如何在构造函数中将 Unique_ptrs 与具有 std::function 作为参数的类对象一起使用
【发布时间】:2022-01-19 16:28:00
【问题描述】:

问题描述

我们有2ABB 有如下构造函数:

B(std::function<std::unique_ptr<A>()> a)

我正在尝试创建一个unique_ptr,就像std::unique_ptr&lt;B&gt; aPtr = std::unique_ptr&lt;B&gt;(new B(std::function&lt;std::unique_ptr&lt;A&gt;())); 一样,我不知道该怎么做。它没有编译,我无法真正解释错误。

如何为 B 类创建 unique_ptr?


// Online C++ compiler to run C++ program online
#include <iostream>
#include <memory>
#include <functional>

class A {
public:
    A(){}
};

class B 
{
public:

    B(std::function<std::unique_ptr<A>()> a):_a(std::move(a)) {}

private:
    std::function<std::unique_ptr<A>()> _a;
};

int main() {
    //std::unique_ptr<B> bPtr = std::unique_ptr<B>(new B(std::function<std::unique_ptr<A>()));

    return 0;
}

【问题讨论】:

  • 您的&lt; 没有关闭&gt;。另外,您希望_a 存储什么功能?它应该是空的吗?
  • 你需要一个A 工厂(std::function&lt;std::unique_ptr&lt;A&gt;()&gt;)作为[](){ return std::make_unique&lt;A&gt;(); }
  • @Jarod42 我更新了代码你能检查一下吗?你是唯一一个做出正确评论的人
  • 不要使用new。改为这样做:unique_ptr&lt;B&gt; bPtr = make_unique&lt;B&gt;([]{ return make_unique&lt;A&gt;(); });

标签: c++ unique-ptr


【解决方案1】:
auto bPtr = std::unique_ptr<B>(new B( std::function< std::unique_ptr<A>() > () ));
//                                     need to close the template         ^
//                                     need to construct an instance of     ^^

使用std::make_unique 会更简单:

auto bPtr = std::make_unique<B>( std::function< std::unique_ptr<A>() >() );
//                                               still as above      ^^^

编辑:对新问题版本的调整:

您尚未提供复制构造函数 - 因此您需要存储 lambda 而不是创建 B 实例:

auto l = []() { return std::make_unique<A>(); };
auto bPtr = std::unique_ptr<B>(new B(l));
// or:
auto ptr  = std::make_unique<B>(l);

请注意,这个新的编辑版本为std::function 对象(lambda!)提供了一个工厂函数,而最初的变体构造了一个没有存储函数的空函数,因此不可调用!

【讨论】:

  • 阿空加瓜谢谢!!!!
【解决方案2】:

您可以通过传递 std::function(或可能转换为的值)来构造 B。

例如合适的 lambda:

B b{[]() { return std::make_unique<A>(); }};

如果你真的想要std::unique_ptr&lt;B&gt;,那就变成:

std::unique_ptr<B> b = std::make_unique<B>([]() { return std::make_unique<A>(); });

【讨论】:

  • 谢谢贾罗德。真的很感激。非常感谢人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-19
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多