使用 make_shared<std::thread 创建 shared_ptr<std::thread> 的实例>

Creating an instance of shared_ptr<std::thread> with make_shared<std::thread>

本文关键字:thread gt std lt shared 实例 make 创建 使用 ptr      更新时间:2023-10-16

请考虑以下代码:

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()替换这个