强制超出范围boost :: bind失败

时间:2014-03-15 22:19:42

标签: c++ boost

我正在尝试创建一个将boost :: function绑定到超出范围的成员函数的示例。即使对象不再存在,仍然可以调用此函数。

我需要证明它不是正确的用途,应用程序需要失败。但是内存位置似乎仍然很明显,所以我需要一种让它失败的方法。

另一个问题是:我是对的吗?有什么我可能会失踪吗?

class bad_object {
    public:
    void fct1() {cout << "Fct 1 called. String value: " << sth << endl;};
    void fct2(int i) {cout << "Fct 2 with param " << i << endl;};
    string sth;
};


int main()
{
    bad_object b;
    boost::function<void ()>    f1(boost::bind( &bad_object::fct1, b ));
    boost::function<void ()>    f2(boost::bind( &bad_object::fct2, b, 10 ));

    boost::function<void ()>    f3;
    {
        bad_object c;
        c.sth = "There once was a cottage";
        f3 = boost::bind( &bad_object::fct1, c );
    }
    // c now goes of scope, f3 should therefore be invalid

    f3();

    return 0;
}

按预期输出。

Fct 1 called. String value:
Fct 2 with param 10
Fct 1 called. String value: There once was a cottage

1 个答案:

答案 0 :(得分:0)

也许您使用weak_ptr Live On Coliru

#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/smart_ptr/make_shared.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>

#include <iostream>

struct X
{
    int foo() const 
    {
        return 42;
    }
    virtual ~X() {
        std::cout << "I'm stepping out here\n";
    }
};

int weak_call(int (X::*ptmf)() const, boost::weak_ptr<X> const& wp) 
{
    auto locked = wp.lock();
    if (!locked)
        throw boost::bad_weak_ptr();

    return ((*locked).*ptmf)();
}

int main()
{
    boost::function<int()> bound_foo;

    {
        auto x = boost::make_shared<X>(); 
        bound_foo = boost::bind(weak_call, &X::foo, boost::weak_ptr<X>(x));

        std::cout << "Bound foo returns: " << bound_foo() << "\n";
    }

    std::cout << "Bound foo returns: " << bound_foo() << "\n";
}

打印:

Bound foo returns: 42
I'm stepping out here
terminate called after throwing an instance of 'boost::bad_weak_ptr'
  what():  tr1::bad_weak_ptr

更通用的版本(允许n-ary成员函数,可选const - 限定)is here (requiring c++11): coliru