Transferring std::thread ownership into a function.

Hello!

I was reading an article about std::thread: http://www.bogotobogo.com/cplusplus/multithreaded4_cplusplus11.php
and the author wrote "If ownership should be transferred into a function, it can just accept an instance of thread by value as one of the parameters" (you can just ctrl + f it). Why would anyone want to do this? Isn't it better to use r-value reference? This way if we use an object and not a temporary the error is going to be about our function and not std::thread constructor, which might be clearer on what is the problem. Are there any benefits when passing by value?

Thanks.
Isn't it better to use r-value reference?

The easiest way to ensure ownership is transferred is to pass by value. Otherwise, you must create a local thread object within the function and move to it from the reference. Why do that when we can have the compiler do it for us?
If I have r-value reference I either have to use temporary or std::move, just as if I used passing by value, the object is going to be moved without new local variable and the interface doesn't change. My VS debugger shows me, that after entering the function, parameter has the same id as the object we passed, no matter if we use thread&& or just thread. They behave the same way for me, so I still don't understand why pass by value. Are there scenarios when with function f(std::thread&& t) the object we pass is not gonna be moved?
I messed around with the code and now I see that r-value reference doesn't mean automatical move of an object:
1
2
3
std::thread a{foo};
std::thread&& b{std::move(a)};
std::thread c = std::move(b);

before 3rd line b and a point to the same thread, after 3rd line thread si moved to c.

I always used to think about references as of pointers with "syntactic sugar". When intelisense told me sizeof(std::thred&&) == 12 I was confused and thought that if reference takes as much space as object itself, than it probably implicitly creates object of std::thread and moves the thread there. Turns out that sizeof(std::thread) == 16 (amd64) and in fact it is a pointer, just my intelisense lied to me. Thanks cire.
Topic archived. No new replies allowed.