【问题标题】:Thread creation using a function of an object in C++在 C++ 中使用对象的函数创建线程
【发布时间】:2015-09-27 15:20:49
【问题描述】:

我是初学者,我正在使用 Visual Studio C++ 2015。我总是看到这样的线程创建:

thread nameThread(functionName);

疑问是:如何创建使用对象的函数成员的线程,并且该函数需要指向另一个对象的属性的指针?像这样的:

if(something == true){
  thread nameThread( object.function( &anotherObject.attribute ) );
}
.
.
.
nameThread.join();

非常感谢。

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    在过去,我们必须使用黑魔法来做到这一点。但是std::thread 足够聪明,可以为我们提供“自动”实现它的重载:

    std::thread nameThread(
       &theTypeOfObject::function,  // function to invoke
       &object,                     // first arg (implicit "this" pointer)
       &anotherObject.attribute     // second arg (first one you see)
    );
    

    【讨论】:

    • &theTypeOfObject::function;很确定 & 符号是必需的。
    • @AlanStokes:是的。它是不需要它的对象指针,想想看,因为那里也可以接受引用(尽管在这种情况下我更喜欢传递一个指针)。
    • 好的,谢谢!我照你说的做了。但我有这个:错误(活动)非静态成员引用必须相对于特定对象labirinto
    • 错误 C2660 'explorador::explorar':函数不接受 0 个参数(explorador::explorar 是 theTypeOfObject::function)
    • @smallCock:你犯了一个错误。你忘了提供论据。
    猜你喜欢
    • 1970-01-01
    • 2017-11-28
    • 2012-05-26
    • 1970-01-01
    • 2019-09-11
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多