std :: function到对象的成员函数和对象的生命周期

Ale*_*cki 6 c++ c++11

如果我有一个实例,std::function它绑定到一个对象实例的成员函数,并且该对象实例超出范围而被破坏,我的std::function对象现在被认为是一个坏指针,如果被调用将会失败?

例:

int main(int argc,const char* argv){
    type* instance = new type();
    std::function<foo(bar)> func = std::bind(type::func,instance);
    delete instance;
    func(0);//is this an invalid call
}
Run Code Online (Sandbox Code Playgroud)

标准中是否有某些内容指明应该发生什么?我的预感是它将抛出异常,因为该对象不再存在

编辑:标准是否指定应该发生什么?

是不确定的行为?

编辑2:

#include <iostream>
#include <functional>
class foo{
public:
    void bar(int i){
        std::cout<<i<<std::endl;
    }
};

int main(int argc, const char * argv[]) {
    foo* bar = new foo();
    std::function<void(int)> f = std::bind(&foo::bar, bar,std::placeholders::_1);
    delete bar;
    f(0);//calling the dead objects function? Shouldn't this throw an exception?

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

运行此代码我收到输出值0;

Bar*_*rry 6

会发生什么是未定义的行为.

bind()调用将返回一些包含副本的对象instance,这样当您调用时func(0)将有效地调用:

(instance->*(&type::func))(0);
Run Code Online (Sandbox Code Playgroud)

取消引用无效指针(如果instancedeleted那样)是未定义的行为.它不会抛出异常(虽然,它是未定义的,所以它可以,谁知道).

请注意,您在通话中错过了占位符:

std::function<foo(bar)> func = 
    std::bind(type::func, instance, std::placeholders::_1);
//                                  ^^^^^^^ here ^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

没有它,func(0)即使使用未删除的实例也无法调用.

更新示例代码以更好地说明正在发生的事情:

struct foo{
    int f;
    ~foo() { f = 0; }

    void bar(int i) {
        std::cout << i+f << std::endl;
    }
};
Run Code Online (Sandbox Code Playgroud)

使用添加的析构函数,您可以看到复制指针(in f)和复制指向(in )的对象之间的区别g:

foo* bar = new foo{42};
std::function<void(int)> f = std::bind(&foo::bar, bar, std::placeholders::_1);
std::function<void(int)> g = std::bind(&foo::bar, *bar, std::placeholders::_1);
f(100); // prints 142
g(100); // prints 142
delete bar;
f(100); // prints 100
g(100); // prints 142 still, because it has a copy of
        // the object bar pointed to, rather than a copy
        // of the pointer
Run Code Online (Sandbox Code Playgroud)