boost::factory with std::map bad function call

I’m having a problem with understanding how boost::factory does its job. The following code will throw in the ctor of test2.

#include <boost/functional/factory.hpp>
#include <boost/function.hpp>

typedef boost::function<A*()> creator;
typedef std::map<string,creator> factory;

class A{
}

class AA : A {
}

class AB : A {
}

class C{
public: 
 C(factory& f);

 factory _f;
}

int main(){
 factory f;
 f["1"] = boost::factory<AA*>();
 f["2"] = boost::factory<AB*>();

 C test(f);
 C test2(f);
}

C::C(factory& f){
  _f = f;
  A* t = _f["1"]();
}

The message is

terminate called after throwing an instance of
‘boost::exception_detail::clone_impl

‘ what(): call to empty boost::function

I think I don’t understand copy/move behaviour here and that is causing the problem.
As far as I understand, the factory gets copied in C::C, so every call to _f[something]() should get its own function to call. But somehow the function is moved out of the factory in the ctor of test, and then I get a bad function call, cause f[“1”] is left in an undefined state.
Please help.


Source: c++

Leave a Reply