眠りネ*_*ネロク 1 c++ ownership-semantics parameter-passing move-semantics c++11
Considering only objects that are movable but non-copyable (e.g., std::thread or std::unique_ptr), I want to transfer the ownership of the resource such an object contains by passing it as an argument to a constructor. I'm comparing two approaches: the constructor taking the object by value vs. by rvalue reference.
As an example with std::thread, consider the following class Value whose constructor takes an std::thread by value:
#include <thread>
#include <utility>
struct Value {
Value(std::thread th): th_(std::move(th)) {}
std::thread th_;
};
Run Code Online (Sandbox Code Playgroud)
The ownership is transferred from the argument object to the parameter object, th, and finally to the data member object, th_.
Consider a similar class, Reference, whose constructor takes in this case an std::thread by rvalue reference:
struct Reference {
Reference(std::thread&& th): th_(std::move(th)) {}
std::thread th_;
};
Run Code Online (Sandbox Code Playgroud)
The ownership is, in this case, transferred from the argument directly to the data member object, th_.
As far as I understand, in the passing-by-value case, both the parameter object and the data member object are move constructed, whereas, for the pass-by-reference case, only the data member is move constructed. To conclude, the latter approach seems to be better since it only requires one move operation, and it is, therefore, more efficient.
Is there, however, any reason to prefer the passing-by-value approach over the passing-by-reference one?
通过值传递是自我记录,而通过引用传递则不是。对读者而言,立即显而易见的是:
(类似地,很难或不可能在实现中犯下导致上述假设无法成立的错误。)
当然,最终这些收益是否超过额外搬家建设的成本这一问题是基于观点的。
(*)当然,这不适用于构造函数在内部执行的移动,即从参数到成员的移动。但是,这里的要点是,调用方可以控制其对象发生的情况:将其移动到构造函数参数中,或者在该步骤发生任何故障的情况下,调用方都可以进行损坏控制(可能会保留损坏的对象)。值)。