【问题标题】:boost::factory with std::map bad function call带有 std::map 错误函数调用的 boost::factory
【发布时间】:2015-08-09 05:07:07
【问题描述】:

我在理解 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"]();
}

消息是

在抛出一个实例后调用终止 'boost::exception_detail::clone_impl

' what(): 调用空 boost::function

我想我不理解这里的复制/移动行为,这就是问题所在。 据我了解,工厂被复制到 C::C 中,因此每次调用 _f[something]() 都应该调用自己的函数。但不知何故,该函数在测试的 ctor 中被移出工厂,然后我得到一个错误的函数调用,导致 f["1"] 处于未定义状态。 请帮忙。

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    据我了解,工厂被复制到 C::C

    是的。

    但不知何故,该函数在 test 的 ctor 中被移出工厂

    不。如果情况似乎如此,您可能在其他地方有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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 1970-01-01
      • 2019-07-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多