强制超出作用域boost::bind失败

Force out of scope boost::bind to fail

本文关键字:bind 失败 boost 作用域      更新时间:2023-10-16

我试图创建一个绑定boost::函数到超出作用域的成员函数的示例。即使对象不再存在,仍然可以调用该函数。

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

另一个问题是:我对吗?我是不是漏掉了什么?

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

也许您使用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 heren";
    }
};
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元成员函数,可选的const限定)在这里(要求c++11): coliru