在visual studio c++上执行编译错误



我使用visual studio c++编写代码。以下是我所写的示例。

我得到以下错误消息。有没有人可以指导我解决下面的错误的建议?

名称空间"std"没有成员线程

#include <iostream>
#include <cstring>
#include<thread>
#include<windows.h>
#include <vector>
#include <thread>
#include <iostream>
using namespace std;
class bar {
public:
void foo() {
std::cout << "hello from member function" << std::endl;
}
};
int main()
{
std::thread t(&bar::foo, bar());
t.join();
}

我也认为你想要启动线程的方式是不可以的。必须首先构造要调用该函数的对象。这个对象需要"活着"比线程的生命周期长。你现在正在做的是试图将bar类的实例作为参数传递给foo成员函数。

提示:在使用线程时,最好也了解lambda。例子:

int main()
{
bar b;
std::thread t([b&]{b.foo()});
t.join();
}
我经常使用shared_ptr<>将数据传递给线程。这意味着线程可以在线程的持续时间内延长对象的生命周期。用于避免传递对实际存在于堆栈中的对象的引用。
int main()
{
auto ptr = std::make_shared<bar>();
std::thread t([ptr]{ptr->foo();}); 
t.join();
}

最新更新