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

标签 c++ c++11

如果我有一个 std::function 的实例,它绑定(bind)到一个对象实例的成员函数,并且该对象实例超出范围,否则将被销毁,我的 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;

最佳答案

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

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

关于c++ - std::function 到对象的成员函数和对象的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28054303/

相关文章:

c++ - Bison C++ : error expected initializer before ‘*’ token

c++ - unique_ptr 的 static_pointer_cast 的替代方案

c++ - 有没有办法让模板函数自动推断迭代器的底层数据类型?

c++ - vector [] 与复制

c++ - 我试图在变量 "height"中添加变量 "media"

c++ - 使用堆栈和迭代器编写后缀计算器

c++ - 标准 C++11 是否保证 std::async(std::launch::async, func) 在单独的线程中启动 func?

C++ 分配器和内存池所有权

c++ - iostream GCC 错误,转换为 boost::filesystem::iostream for Windows

c++ - Cuda C++:Device上的Malloc类,并用主机中的数据填充