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? 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){};
}
The difference between pass-by-reference and pass-by-pointer is that pointers can be NULL or reassigned whereas references cannot. Use pass-by-pointer if NULL is a valid parameter value or if you want to reassign the pointer. Otherwise, use constant or non-constant references to pass arguments.
References are usually preferred over pointers whenever we don't need “reseating”. Overall, Use references when you can, and pointers when you have to. But if we want to write C code that compiles with both C and a C++ compiler, you'll have to restrict yourself to using pointers.
If you have used std::thread or std::bind , you probably noticed that even if you pass a reference as parameter, it still creates a copy instead. From cppreference, The arguments to the thread function are moved or copied by value.
As a rule passing by const reference is better. But if you need to modify you function argument locally you should better use passing by value. For some basic types the performance in general the same both for passing by value and by reference.
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.*
Using std::ref
may help in cases where you have a named object instance rather than this
, since this
is quite easy to spell. But consider the following situation, in which you'd like to stay nicely 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. Defects are things that "were always meant to be the way we say now".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With