简体   繁体   中英

What's the difference between ( this ) and ( std::ref(*this) )

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?

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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