简体   繁体   English

std :: thread构造函数传递指针和传递ref之间有区别吗?

[英]std::thread constructor Is there a difference between passing a pointer and passing by ref?

When creating a thread that calls a member function, is there a difference between passing a pointer to the current class or passing a reference? 在创建调用成员函数的线程时,将指针传递给当前类或传递引用是否有区别?

From the example below, does method1 behave the same as method2? 从下面的例子中,method1的行为与method2相同吗? Are there any differences? 有什么不同吗?

class MyClass
{
public:
    MyClass(){};
    ~MyClass(){};
    void memberFunction1()
    {
        //method 1
        std::thread theThread(&MyClass::memberFunction2, this, argumentToMemberFunction2)

        //method 2
        std::thread theThread(&MyClass::memberFunction2, std::ref(*this), argumentToMemberFunction2)
    }
    void memberFunction2(const double& someDouble){};
}

No, there are no differences, but note that using a reference wrapper has only become possible with the acceptance of LWG 2219 as a defect report at the Oct 2015 WG21 meeting.* 不,没有差异,但请注意,只有在2015年10月WG21会议上接受LWG 2219作为缺陷报告,才能使用参考包装。*

Using std::ref may help in cases where you have a named object instance rather than this , since this is quite easy to spell. 使用std::ref可能有助于你有一个命名对象实例而不是this ,因为this很容易拼写。 But consider the following situation, in which you'd like to stay nicely const-correct: 但请考虑以下情况,您希望保持良好的const-correct:

A a;
std::thread(&A::foo, std::cref(a), 1, 2);

This may be easier to read than: 这可能比以下更容易阅读:

std::thread(&A::foo, &(const_cast<const A&>(a)), 1, 2);
std::thread(&A::foo, &as_const(a), 1, 2);
std::thread(&A::foo, const_cast<const A*>(&a), 1, 2);

*) Vendors that keep distinct language dialects around, like GCC's and Clang with the -std flag), will typically consider defects to apply to all dialects and "fix" the implementations. *)保持不同语言方言的供应商,如GCC和带有-std标志的Clang),通常会考虑将缺陷应用于所有方言并“修复”实现。 Defects are things that "were always meant to be the way we say now". 缺陷是“总是意味着我们现在说的方式”。

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

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