以下代码的行为是否定义明确? f()
调用的行为如何?
#include <functional>
#include <iostream>
struct A
{
void shout()
{
std::cout <<"shout";
}
};
int main()
{
std::function<void()> f;
{
A a;
f = std::bind(&A::shout, &a);
}
f(); // what happens here?
}
最佳答案
您的代码最终会在函数包装器中存储一个悬空引用(指向一个不再存在的对象),并且调用该函数会导致未定义的行为。
如果原始对象的生命周期不如包装器那么长,您始终可以在包装器中存储该对象的拷贝:
f = std::bind(&A::shout, a);
// ^^^ copy
关于c++ - 当绑定(bind)对象过期时,由 std::bind 创建的仿函数的行为是否定义明确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37000978/