【发布时间】:2015-01-20 20:10:59
【问题描述】:
如果我有一个绑定到对象实例的成员函数的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;
【问题讨论】:
-
你的意思是这是未定义的行为还是什么?
-
是的,因为您使用的是指针。如果您绑定对象本身,则会复制 IIRC。
-
它是未定义的行为,还是我可以预期会发生什么......一个例外,它会起作用......别的东西。我是在理论上提出这个问题的。