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

时间:2015-01-20 20:10:59

标签: 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
}

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

编辑: 标准是否规定了应该发生的事情?

是不确定的行为?

编辑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;
}

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

1 个答案:

答案 0 :(得分:6)

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

bind()调用将返回一些包含instance副本的对象,以便在您致电func(0)时有效致电:

(instance->*(&type::func))(0);

取消引用无效指针,就像instancedelete d时那样,是未定义的行为。它不会抛出异常(虽然它是未定义的,所以它可以,谁知道)。

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

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

如果不这样,即使使用未删除的实例,也无法调用func(0)

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

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

    void bar(int i) {
        std::cout << i+f << std::endl;
    }
};

使用添加的析构函数,您可以看到复制指针(在f中)和复制指向的对象(在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
相关问题