I imagine std::move() has a bit more of a performance cost in the context of something like:
std::thread thrd(&func, this);
someArrOfThreads[0] = std::move(thrd);
vs
std::thread *thrd = new std::thread(&func, this);
someArrOfThreadPointers[0] = thrd;
Is this true? And if so, is it a matter of std::move() changes the boundaries of memory of the thread or something else?
I realize there is the difference that in the first I am actually assigning a value of the array to the thread, and the other being the pointer to the thread, the thread stays in its address(es) in the second.
17
The only thing that std::move does is turn a lvalue into an rvalue reference. This then causes the rvalue reference version of the assignment operator to be called. From a code generation point of view it is a noop.
The rvalue overload is likely to be more efficient since it is allowed to move class internal as opposed to performing a deep copy.
How threads are implemented is very platform specific. However classes that implement move semantics typically hold only a handle for or pointer to the actual objects they manage.
For that reason the std::move is likely to be doing something similar to your pointer example on the inside. You can generally expect moving objects to be efficient.
Looking at how std::thread is implemented in GCC on Linux it apparently contains one data item a solitary unsigned long int which is the handle to a thread using the <pthreads> library.
When you do someArrOfThreads[0] = std::move(thrd); it simply swaps the thread's handle with the one in the array.
That should be pretty fast and you don't have the constant overhead of using indirection that you would have if you were using pointers.
Even though implementations may differ the std::move version using values rather than the pointer has to be preferred.
Typically move semantics are as fast as (and possibly faster than) using pointers but also they are generally safer and less fiddly.
new will be slower because it uses the heap. Storing instance(s) of std::thread in an object will be able to take advantage of the time spent in the allocation of its container, which may have also been near zero cost because it might be a local variable or have static lifetime.
Also, new will have poorer locality than a member variable or local variable, the instance could end up anywhere in memory. Accessing the heap might require a lock to be acquired, severely reducing performance.
Don't downgrade to C style code because you think you will save nanoseconds. You won't.
Comments
Explore related questions
See similar questions with these tags.
