简体   繁体   English

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

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

Consider the following code: 请考虑以下代码:

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()
{
    ...
}

I'm trying to initialise the shared pointer mThread so that it calls the function Step . 我正在尝试初始化共享指针mThread,以便它调用函数Step However, the compiler gives me the error " invalid initialization of reference of type ... from expression of type 'unresolved overloaded function type' ". 但是,编译器给出了错误“ 类型的引用的无效初始化...从类型'未解析的重载函数类型'的表达式 ”。 Obviously I'm doing something stupid, but I can't put my finger on it. 显然我做了一些愚蠢的事,但我不能把手指放在上面。 Can anybody help? 有人可以帮忙吗? Thanks in advance! 提前致谢!

Step() is a non-static member function, so it has an implicit first parameter of type A* . Step()是一个非静态成员函数,因此它有一个隐式的第一个参数A* You need to bind the current instance of A when invoking it. 您需要在调用时绑定A的当前实例。

mThread = std::make_shared<std::thread>(std::bind(&A::Step, this));

You can also use a lambda instead of bind 您也可以使用lambda而不是bind

mThread = std::make_shared<std::thread>([this]{ Step(); });

As @Casey points out in the comments, std::thread 's constructor has special treatment for pointer to member functions, and will assume the first following argument is a pointer or reference to the instance on which to call the member function. 正如@Casey在注释中指出的那样, std::thread的构造函数对指向成员函数的指针有特殊处理,并假设第一个后面的参数是指向要调用成员函数的实例的指针或引用。 This means you can avoid bind and directly pass this as the second argument. 这意味着您可以避免bind并直接将this作为第二个参数传递。

mThread = std::make_shared<std::thread>(&A::Step, this);

Try (use labda instead of the free function): 尝试(使用labda而不是自由函数):

mThread=make_shared<std::thread>([this](){ Step(); }); 

The way it is, you're not passing a reference to this to the constructor inspite of it being a member function. 它是这样的,尽管它是一个成员函数,但你并没有将它的引用传递给构造函数。

This solution uses a lambda to create a function-object that takes no parameters but has a reference to this. 此解决方案使用lambda创建一个函数对象,该函数对象不带参数,但具有对此的引用。

If you want to use the global function do this instead, and move void Step() to before it's usage: 如果你想使用全局函数,请执行此操作,并在使用之前将void Step()移动到:

mThread=make_shared<std::thread>(::Step()); 

the :: removes the ambiguity over the scope of the function. ::删除了函数范围的歧义。

您应该使用shared_from_this()替换它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM