Saurav Sahu
Saurav Sahu

Reputation: 13924

std::move operation C++

Lines from Anthony Williams book:

The following example shows the use of std::move to transfer ownership of a dynamic object into a thread:

void process_big_object(std::unique_ptr<big_object>);

std::unique_ptr<big_object> p(new big_object);
p->prepare_data(42);
std::thread t(process_big_object,std::move(p));

By specifying std::move(p) in the std::thread constructor, the ownership of the big_object is transferred first into internal storage for the newly created thread and then into process_big_object.

I understand stack and heap; any idea, what actually is this internal storage ?

Why can't they transfer the ownership directly to process_big_object?

Upvotes: 6

Views: 813

Answers (3)

Solomon Slow
Solomon Slow

Reputation: 27115

Why can't they transfer the ownership directly to process_big_object?

Because there is no line in the code snippet where process_big_object is called as a function. The last line of the snippet calls the std::thread constructor. It will set in motion a chain of events that eventually will cause process_big_object(p) to be called in the new thread; but that call is not visible here.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

All arguments to a thread are copied into some internal memory held by the std::thread object, so it can be passed to the thread function.

That internal memory is owned by the std::thread object, before the ownership is passed on to the actual thread function.

Upvotes: 8

user4442671
user4442671

Reputation:

It means that the object will temporarily belong to the std::thread object until the thread actually starts.

Internal storage here refers to the memory associated to the std::thread object. It could be a member variable, or just held in the stack during the constructor. Since this is implementation dependant, the general, and non-commital, "internal storage" term is used.

Upvotes: 12

Related Questions