使用 make_shared<std::thread 创建 shared_ptr<std::thread> 的实例>
Creating an instance of shared_ptr<std::thread> with make_shared<std::thread>
请考虑以下代码:
class A
{
....
shared_ptr<std::thread> mThread;
void Step();
void LaunchTrhead();
}
void A::LaunchThread()
{
...
mThread=make_shared<std::thread>(Step); // This line gives an error
...
}
void A::Step()
{
...
}
我正在尝试初始化共享指针 mThread,以便它调用函数 Step。但是,编译器给了我错误"类型引用的初始化无效......来自类型为"未解析的重载函数类型"的表达式"。显然我在做一些愚蠢的事情,但我不能把手指放在上面。有人可以帮忙吗?提前感谢!
Step()
是一个非静态成员函数,因此它具有类型为 A*
的隐式第一个参数。调用 A
时,需要绑定当前的实例。
mThread = std::make_shared<std::thread>(std::bind(&A::Step, this));
您也可以使用 lambda 代替 bind
mThread = std::make_shared<std::thread>([this]{ Step(); });
正如@Casey在注释中指出的那样,std::thread
的构造函数对指向成员函数的指针具有特殊处理,并且将假定以下第一个参数是指向调用成员函数的实例的指针或引用。这意味着您可以避免bind
并直接传递this
作为第二个参数。
mThread = std::make_shared<std::thread>(&A::Step, this);
尝试(使用 labda 而不是 free 函数):
mThread=make_shared<std::thread>([this](){ Step(); });
就是这样,你不会把对这个的引用传递给构造函数,尽管它是一个成员函数。
此解决方案使用 lambda 创建一个函数对象,该对象不带参数,但对此有引用。
如果要使用全局函数,请改为执行此操作,并在使用之前void Step()
移动到
mThread=make_shared<std::thread>(::Step());
该::
消除了函数范围的歧义。
你应该使用shared_from_this()
替换这个
相关文章:
- 在std::thread中,joinable()然后join()线程安全吗
- EASTL矢量<向量<int>>连续的
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 分离一个静态常量 std::thread?
- 尝试使用 std::vector<std::thread时出现静态断言失败错误>
- 使用 thread 类在 C++ 中构造线程的动态数组时出错
- 当指向对象的指针作为参数传递给 std::thread 时,内存可见性
- 如何从 std::thread 返回值
- 在C++中使用并行化的预期速度是多少(不是 OpenMp,而是 <thread>)
- 将 std::thread by 值推送到列表中
- 转发变量参数列表以模拟 std::thread
- 嵌入式设备 -> std::thread -> FreeRTOS?
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- std::thread 增加 DLL 引用计数,从而防止卸载 DLL
- 如何防止 std::thread 在 QT 中冻结 GUI?
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- C++ - Thread Pool
- 为什么参数在构造 std::thread 时移动两次
- std::thread::_Invoker 使用线程编程时出错
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接