0
点赞
收藏
分享

微信扫一扫

「 C++ 11」std::thread “invalid use of non-static member function“问题处理


文章目录

  • ​​🟠问题简述:​​
  • ​​🟡处理思路:​​
  • ​​🔴 方法一​​
  • ​​🟢C++代码:​​
  • ​​🔵结果展示:​​
  • ​​🔴 方法二​​
  • ​​🟢C++代码:​​
  • ​​🔵结果展示:​​
  • ​​🟣引经据典:​​

🟠问题简述:

项目中使用​​std::thread​​​把类的成员函数作为线程函数,在编译的时候报错了:​​"invalid use of non-static member function"​​,于是研究了一番,于是就产生了这篇博文,记录一下。

错误示例

#include <iostream>
#include <thread>
#include <stdlib.h>

using namespace std;

class Test
{
public:
void testDemo()
{
cout << "hello world." << endl;
};
};


int main()
{
Test myTest;
std::thread t(myTest.testDemo);
t.join();
return 0;
}

问题展示

main.cpp: In function ‘int main()’:
main.cpp:31:26: error: invalid use of non-static member function ‘void Test::testDemo()’
31 | std::thread t(myTest.testDemo);
| ~~~~~~~^~~~~~~~
main.cpp:18:10: note: declared here
18 | void testDemo()
|

🟡处理思路:

🔴 方法一

根据std::thread构造函数进行传参。

  • 类成员函数的指针
    当std::thread内部创建新线程时,它将使用传入的成员函数作为线程函数。
  • 类的指针
    在每个非静态成员函数中,第一个参数始终是指向其自身类对象的指针。因此,线程类将在调用传递的成员函数时将这个指针作为第一个参数传递。

🟢C++代码:

/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <iostream>
#include <thread>
#include <stdlib.h>

using namespace std;

class Test
{
public:
void testDemo()
{
cout << "hello world." << endl;
};
};

int main()
{
Test myTest;
std::thread t(&Test::testDemo, &myTest);
t.join();
return 0;
}

🔵结果展示:

hello world.

🔴 方法二

把线程函数修改为静态成员函数
因为静态函数不与类的任何对象相关联。因此,我们可以直接将类的静态成员函数作为线程函数传递,而无需传递任何指向对象的指针。

🟢C++代码:

/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <iostream>
#include <thread>
#include <stdlib.h>

using namespace std;

class Test
{
public:
static void testDemo()
{
cout << "hello world." << endl;
};
};

int main()
{
Test myTest;
std::thread t(myTest.testDemo);
t.join();
return 0;
}

🔵结果展示:

hello world.

🟣引经据典:

​​https://thispointer.com/c11-start-thread-by-member-function-with-arguments/​​ https://cplusplus.com/reference/thread/thread/


举报

相关推荐

0 条评论