使用成员函数启动线程应该传递对象,指针或参考?
我对使用成员函数启动线程感到困惑。我知道我需要将类对象作为第二个参数传递。但是有人将对象传递给thread()
,然后有人通过了一个地址,我试图通过参考。他们俩都在编译正常。因此,我对哪个是正确的困惑。
class X
{
public:
void do_lengthy_work(){
std::cout << "1:1" << std::endl;
}
};
int main(){
X my_x;
std::thread t(&X::do_lengthy_work, std::ref(my_x)); // pass reference
std::thread t(&X::do_lengthy_work, &my_x); // pass address
std::thread t(&X::do_lengthy_work, my_x); // pass object
t.join();
return 0;
}
I'm confused about starting a thread with a member function. I know I need to pass a class object as the second parameter. But someone passed the object to the thread()
, and someone passed an address, and I had tried to pass a reference. Both of them are compiling OK. So I am confused about which one is correct.
class X
{
public:
void do_lengthy_work(){
std::cout << "1:1" << std::endl;
}
};
int main(){
X my_x;
std::thread t(&X::do_lengthy_work, std::ref(my_x)); // pass reference
std::thread t(&X::do_lengthy_work, &my_x); // pass address
std::thread t(&X::do_lengthy_work, my_x); // pass object
t.join();
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
线程构造器开始根据
std ::::::::std ::::::::调用
。因此,您显示的所有代码行都将做点什么。如果对象的寿命比线程的寿命更长,则前两行(参考和指针)很好。从上面的链接到
std :: Invoke
,它们是等效的。否则,第三行将对象复制到线程中。这意味着现在原始对象无关紧要,并且可以被销毁,但也意味着在原始对象(仅副本)中不会看到任何结果。The thread constructor begins executing the thread according to the rules of
std::invoke
. So all 3 of the lines of code you show will do something.The first two lines (ref and pointer) are fine if you expect the lifetime of the object to be longer than the lifetime of the thread. As you can see from the link to
std::invoke
above, they are equivalent. Otherwise, the third line copies the object into the thread. This means that the original object now doesn't matter and can be destroyed, but also means that any results will not be visible in the the original object, only the copy.