std::thread constructor 传递指针和传递ref有区别吗?
std::thread constructor Is there a difference between passing a pointer and passing by ref?
创建调用成员函数的线程时,传递指向当前的指针class和传递引用有区别吗?
从下面的示例中,方法 1 的行为是否与方法 2 相同?有什么不同吗?
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){};
}
不,没有区别,但请注意,只有在 2015 年 10 月 WG21 会议上接受 LWG 2219 作为缺陷报告后,才有可能使用参考包装器。*
使用 std::ref
可能会在您有命名实例 object 而不是 this
的情况下有所帮助,因为 this
很容易拼写。但是请考虑以下情况,您希望在这种情况下保持良好状态const-correct:
A a;
std::thread(&A::foo, std::cref(a), 1, 2);
这可能比以下更容易阅读:
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);
*) 保留不同语言方言的供应商,例如带有 -std
标志的 GCC 和 Clang),通常会考虑将缺陷应用于所有方言,"fix"实施。缺陷是 "were always meant to be the way we say now".
创建调用成员函数的线程时,传递指向当前的指针class和传递引用有区别吗?
从下面的示例中,方法 1 的行为是否与方法 2 相同?有什么不同吗?
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){};
}
不,没有区别,但请注意,只有在 2015 年 10 月 WG21 会议上接受 LWG 2219 作为缺陷报告后,才有可能使用参考包装器。*
使用 std::ref
可能会在您有命名实例 object 而不是 this
的情况下有所帮助,因为 this
很容易拼写。但是请考虑以下情况,您希望在这种情况下保持良好状态const-correct:
A a;
std::thread(&A::foo, std::cref(a), 1, 2);
这可能比以下更容易阅读:
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);
*) 保留不同语言方言的供应商,例如带有 -std
标志的 GCC 和 Clang),通常会考虑将缺陷应用于所有方言,"fix"实施。缺陷是 "were always meant to be the way we say now".