c++ - 仅当将 lambda 中捕获的 var 传递给 pthread_create 时才编译错误

标签 c++ c++11

在下面的代码中,我让 pthread_create 使用 lambda 调用类函数(同样可以使用函数指针来完成)。前两个编译正常,但第三个编译错误,看起来像是试图将指向类成员的指针转换为 C 类型函数。不确定。

#include <pthread.h>


class threadtest
{
private:
    void* thread1()            { return nullptr; }
    void* thread2( void* p )   { return p;       }


public:
    void start();
};

void threadtest::start()
{
   pthread_t thd0;
   auto fn0 = []( void* a_pArg ) -> void* { return static_cast<threadtest*>( a_pArg )->thread1(); };
   pthread_create( &thd0, NULL, fn0, (void*)this );

   pthread_t thd1;
   auto fn1 = []( void* a_pArg ) -> void* { void* p = nullptr; return static_cast<threadtest*>( a_pArg )->thread2( p ); };
   pthread_create( &thd1, NULL, fn1, (void*)this );

   pthread_t thd2;
   void* p;
   auto fn3 = [p]( void* a_pArg ) -> void* { return static_cast<threadtest*>( a_pArg )->thread2( p ); };
   pthread_create( &thd2, NULL, fn3, (void*)this );
}

这是错误:

threadtest.cpp: In member function ‘void threadtest::start()’:
threadtest.cpp:31:50: error: cannot convert ‘threadtest::start()::__lambda2’ to ‘void* (*)(void*)’ for argument ‘3’ to 
‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’
pthread_create( &thd2, NULL, fn3, (void*)this );

编译器版本为:gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

在我的实际代码中,我没有执行第二个或第三个示例。我知道当线程访问它时,var 从堆栈中退出时存在竞争条件。我很好奇为什么编译器会在捕获任何 var 时抛出错误?有什么变化?

谢谢

最佳答案

名为 fn3 的 lambda 表达式捕获变量 p。只有无捕获 lambda 定义到函数指针的转换。

引用 N3337,§5.1.2/6 [expr.prim.lambda]

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.

因此,当您尝试在对 pthread_create 的调用中将 lambda 转换为函数指针时,它会失败。


这是不允许的,因为函数指针无法携带已被 lambda 捕获的状态。

关于c++ - 仅当将 lambda 中捕获的 var 传递给 pthread_create 时才编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27339123/

相关文章:

c++ - 为什么 const 函数返回左值而不是右值?

python - 在 C++ 中嵌入 python 时出现模块问题

c++ - 如何使用 GUI 将外部库和项目导入我的 C++ 项目?

c++ - 如何确保 C++ 类模板中非静态数据成员的正确初始化

c++ - 编译器差异 : Interaction between alias resolution and name lookup

c++ - 在一个函数容器中存储和调用不同参数的函数

c++ - 派生模板类

c++ - QT 插槽和信号失败

基于其他元素大小的 C++ union 元素大小

c++ - 澄清想要重新。 C++ 类型特征