将方法与对象指针绑定并在之后删除对象,该方法仍然是可调用的。
struct A {
void b(){std::cout << "SUHDU" << std::endl;}
};
int main(int argc, const char * argv[])
{
A *a = new A;
auto f1 = std::bind(&A::b, a);
auto f2 = std::bind(&A::b, std::ref(a));
f1();
f2();
delete a;
f1(); // still outputs SUHDU
f2(); // still outputs SUHDU
}
std::bind
为什么会这样做,它是如何做到的?
这是未定义的行为。它存储参数的副本,在您的情况下,A*
后来无效。此提示还会导致修复: 要使您的示例合法,请使用 std::shared_ptr
:
struct A {
void b(){std::cout << "SUHDU" << std::endl;}
};
int main(int argc, const char * argv[])
{
auto a = std::make_shared<A>();
auto f1 = std::bind(&A::b, a);
f1();
a.reset();
f1(); // still outputs SUHDU
}
当然,这将使您的对象保持活动状态,直到f1
超出范围。