1

I used to create a thread in this way

std::thread(&A::Func, this);

But I find there's another way

std::thread(&A::Func, std::ref(*this));

What's the difference between them?

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

2 Answers2

2

In the context of launching a thread running a member function of a class A, those calls are equivalent.

The first is like

void compiler_created_on_new_thread(A * a) { a->Func(); }

The second is like

void compiler_created_on_new_thread(A & a) { a.Func(); }

If instead A were a namespace, they would be distinguishable

namespace A {
    void Func(Thing *) { std::cout << "pointer"; }
    void Func(Thing &) { std::cout << "reference"; }
}

The first would display "pointer" and the second "reference"

Caleth
  • 52,200
  • 2
  • 44
  • 75
0

std::ref is a true reference that means if you access this on the thread you started it also changes the object on the other thread. the other way as well. Pointers can do this as well but could be handled different by the compiler. Just a word of advice: you should be careful to access an object from two threads and use std::mutex.

just a guy
  • 137
  • 7
  • yes but it is as far as I know the only way to get a reference instead of a pointer which can be handled differently by the compiler to increase efficence – just a guy Mar 04 '21 at 09:16
  • 2
    Most compilers implement references using pointers, and std::ref creates a wrapper object so it is most likely less efficient. References were added to support operator overloading, in this case it makes no difference what syntax you chose. One benefit of reference here might be that it can't be null. – rmfeldt Mar 04 '21 at 09:30
  • 1
    It's not a "true reference". It's a `reference_wrapper`, which is a stdlib class that stores a pointer internally. It's useful for plenty cases where one needs a reference but also needs assignability / the ability to store in container, but it's still implemented using a pointer. And even real references are typically implemented that way if they need passed around. So the idea that reference vs pointer could matter for optimisation very needs a citation. – underscore_d Mar 04 '21 at 09:37