我在理解boost :: factory如何完成其工作时遇到问题。以下代码将引入test2的ctor。
#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"]();
}
消息是
在抛出一个实例后终止调用 &#39;升压:: exception_detail :: clone_impl
&#39; what():调用空boost :: function
我想我不明白这里的复制/移动行为,这就是导致问题的原因。
据我所知,工厂被复制到C :: C中,因此每次调用_f[something]()
都应该有自己的函数来调用。但不知何故,该函数在测试的ctor中被移出工厂,然后我得到一个错误的函数调用,因为f [&#34; 1&#34;]处于未定义状态。
请帮忙。
答案 0 :(得分:0)
据我了解,工厂被复制到C :: C
是
但不知何故,该功能在测试中被移出了工厂
不。如果情况确实如此,那么您可能在其他地方Undefined Behaviour。或者你可能正在运行一个不同的(错误)版本的boost(这似乎不太可能)。
看看你是否可以使用此处显示的代码重现它:
<强> Live On Coliru 强>
#include <boost/functional/factory.hpp>
#include <boost/function.hpp>
#include <map>
#include <iostream>
struct A {};
struct AA : A {
AA() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};
struct AB : A {
AB() { std::cout << __PRETTY_FUNCTION__ << "\n"; }
};
typedef boost::function<A*()> creator;
typedef std::map<std::string, creator> factory;
struct C {
C(factory &f){
_f = f;
for (auto& e : _f)
std::cout << "entry for " << e.first << " present " << (!!e.second) << "\n";
}
factory _f;
};
int main() {
factory f;
f["1"] = boost::factory<AA*>();
f["2"] = boost::factory<AB*>();
C test(f);
delete f["1"]();
delete f["2"]();
delete f["1"]();
delete f["2"]();
C test2(f);
delete f["1"]();
delete f["2"]();
delete f["1"]();
delete f["2"]();
}
打印
entry for 1 present 1
entry for 2 present 1
AA::AA()
AB::AB()
AA::AA()
AB::AB()
entry for 1 present 1
entry for 2 present 1
AA::AA()
AB::AB()
AA::AA()
AB::AB()