我一直以为std::bind函数在给某个函数绑定参数时,如果参数是栈变量,且是类对象,等实际调用std::bind函数时,因为传递的栈变量参数已经不存在了,会导致程序崩溃,但实际上并不是这样,看代码:
#include <functional> #include <iostream> class A { public: A() { k = 11; std::cout << "A constructor" << std::endl; } A(const A& rhs) { std::cout << "A copy constructor" << std::endl; k = rhs.k; } ~A() { std::cout << "A destructor" << std::endl; } public: int k; }; void f1(int i, int j, A a) { std::cout << "k=" << a.k << ", i=" << i << ", j=" << j << std::endl; } int main() { A* pa = new A(); auto fx = std::bind(f1, 9, 10, *pa); delete pa; fx(); return 0; } 上述代码中pa在绑定函数后立刻被销毁,但是实际调用fx时,并没有发生崩溃,输出结果一切正常。这说明A对象发生了拷贝。所以,std::bind可以放心大胆地绑定栈变量。
关于std::bind的原理参见: http://www.cnblogs.com/xusd-null/p/3698969.html