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