std::move 运行C++
std::move operation C++
安东尼·威廉姆斯书中的台词:
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
.
我了解堆栈和堆;知道吗,这个 internal storage 到底是什么?
为什么他们不能将所有权直接转让给 process_big_object
?
表示该对象会暂时属于std::thread
对象,直到线程真正启动。
这里的内部存储是指与std::thread
对象关联的内存。它可以是一个成员变量,或者只是在构造函数期间保存在堆栈中。由于这是依赖于实现的,因此使用了一般的和非承诺的 "internal storage" 术语。
线程的所有参数都被复制到 std::thread
对象持有的一些内部内存中,因此它可以传递给线程函数。
在将所有权传递给实际线程函数之前,该内部内存由 std::thread
对象拥有。
Why can't they transfer the ownership directly to process_big_object
?
因为代码片段中没有一行将 process_big_object
作为函数调用。代码片段的最后一行调用 std::thread
构造函数。它将启动一系列事件,最终导致 process_big_object(p)
在新线程中被调用;但该调用在此处不可见。
安东尼·威廉姆斯书中的台词:
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 thestd::thread
constructor, the ownership of thebig_object
is transferred first into internal storage for the newly created thread and then intoprocess_big_object
.
我了解堆栈和堆;知道吗,这个 internal storage 到底是什么?
为什么他们不能将所有权直接转让给 process_big_object
?
表示该对象会暂时属于std::thread
对象,直到线程真正启动。
这里的内部存储是指与std::thread
对象关联的内存。它可以是一个成员变量,或者只是在构造函数期间保存在堆栈中。由于这是依赖于实现的,因此使用了一般的和非承诺的 "internal storage" 术语。
线程的所有参数都被复制到 std::thread
对象持有的一些内部内存中,因此它可以传递给线程函数。
在将所有权传递给实际线程函数之前,该内部内存由 std::thread
对象拥有。
Why can't they transfer the ownership directly to
process_big_object
?
因为代码片段中没有一行将 process_big_object
作为函数调用。代码片段的最后一行调用 std::thread
构造函数。它将启动一系列事件,最终导致 process_big_object(p)
在新线程中被调用;但该调用在此处不可见。