
class Testc { public: void fun1(int *&p) { p = new int(); *p =2; } void fun2() { std::thread t([=] {(fun1)( p);}); if(t.joinable()) t.detach(); } int *p; }; fun1 的参数是引用传递,为什么 fun2 用[=]捕获编译通过,特殊在于参数是类的成员。
如果把 fun1 移到全局函数,为什么 fun2 用[this]捕获也编译通过
void fun1(int *&p) { p = new int(); *p =2; } class Testc { public: void fun2() { std::thread t([this] {(fun1)( p);}); if(t.joinable()) t.detach(); } int *p; }; 就有点懵逼了
1 auto8888 OP 刚试了一下,貌似用引用捕获也不能修改外部变量??? 我,裂开来 |
2 morningtzh 2021 年 3 月 30 日 |
3 mogg 2021 年 3 月 30 日 不太懂,楼主想问什么? 这里有一个作用域的概念,闭包里的 fun1,p 其实是 this.fun1,this.p 测试了一下( detach 改成 join ),没什么问题啊…… 测试代码 https://paste.ubuntu.com/p/HrsHf5zSXS/ |