Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading