【问题标题】:std::function to member function of object and lifetime of objectstd::function 到对象的成员函数和对象的生命周期
【发布时间】: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。
  • 它是未定义的行为,还是我可以预期会发生什么......一个例外,它会起作用......别的东西。我是在理论上提出这个问题的。

标签: c++ c++11


【解决方案1】:

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

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

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

如果instancedeleted 则取消引用无效指针是未定义的行为。它不会抛出异常(尽管它是未定义的,所以它可以,谁知道呢)。

请注意,您的通话中缺少占位符:

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

【讨论】:

  • @Barry 代码只是一个例子,但是感谢占位符是必需的。标准中有什么地方我可以参考吗?
  • @AlexZywicki 查看this old question
  • 至少在 POD 指针类型的情况下,行为是未定义的。 std::function 类型是否在内部解析为指针?
  • @AlexZywicki 您可以将std::function&lt;R(Args...)&gt; 视为具有一些内部私有类型placeholdervirtual R call(Args...) = 0; 将由一些特定的holder&lt;T&gt; 实现,其中包含您构造它的T .无论您的库如何实现它,它都是std::function 工作原理的合理思维模型。
  • 它是复制您绑定到的对象的实例,还是持有对该对象的指针/引用。我只是试了一下,如果对象不再存在,它不会以任何方式破坏......这让我相信它正在制作副本。
猜你喜欢
  • 2023-02-07
  • 2015-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
相关资源
最近更新 更多