use*_*622 9 c++ multithreading pointers member-functions pass-by-reference
在创建调用成员函数的线程时,将指针传递给当前类或传递引用是否有区别?
从下面的例子中,method1的行为与method2相同吗?有什么不同吗?
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){};
}
Run Code Online (Sandbox Code Playgroud)
不,没有差异,但请注意,只有在 2015 年 10 月的 WG21 会议上接受LWG 2219作为缺陷报告后,才能使用参考包装器。*
std::ref如果您有一个命名对象实例而不是,使用可能会有所帮助this,因为this它很容易拼写。但请考虑以下情况,在这种情况下您希望保持良好的常量正确性:
A a;
std::thread(&A::foo, std::cref(a), 1, 2);
Run Code Online (Sandbox Code Playgroud)
这可能比以下内容更容易阅读:
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);
Run Code Online (Sandbox Code Playgroud)
*) 保留不同语言方言的供应商(例如带有标志的 GCC 和 Clang -std),通常会考虑将缺陷应用于所有方言并“修复”实现。缺陷是“本来就应该是我们现在所说的”的东西。