Home > Enterprise >  How can I use Unique_ptrs with an class object having std::function as argument in the constructor
How can I use Unique_ptrs with an class object having std::function as argument in the constructor

Time:01-20

Problem Description

We have 2 classes A and B. B has the following constructor:

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

I am trying to create a unique_ptr as in std::unique_ptr<B> aPtr = std::unique_ptr<B>(new B(std::function<std::unique_ptr<A>())); I can't figure out how to do it. It's not compiling and I can't really explain the error.

How Can I create unique_ptr for class B?


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

CodePudding user response:

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     ^^

You get the same a bit simpler by using std::make_unique:

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

Edit: Adjustment to new question version:

You have not yet provided a copy constructor – so you need to store the lambda instead of creating a B instance:

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

Note that this new edited version provides a factory function to the std::function object (the lambda!), while the initial variants constructed an empty one without function stored inside, so not callable!

CodePudding user response:

You might construct a B by passing a std::function (or value which might convert to).

For example appropriate lambda:

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

If you really want std::unique_ptr<B>, then it becomes:

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