According to the core guidelines:
F.18: For “will-move-from” parameters, pass by X&& and std::move the parameter
The example is:
void sink(vector<int>&& v) { // sink takes ownership of whatever the argument owned
// usually there might be const accesses of v here
store_somewhere(std::move(v));
// usually no more use of v here; it is moved-from
}
I noticed that I tend to use smart pointers for all objects except cheaply-copied (which I almost always consider only primitives). So I almost always use the following guidelines:
void sink(std::unique_ptr<OtherThanPrimitive> p) {
// use p ... possibly std::move(p) onward somewhere else
} // p gets destroyed
I started to consider if I use best practice. What I can think of as advantage of the first approach is forcing caller of a function to explicitly std::move and it makes code cleaner. In the second approach move constructor will be called two times, but for smart pointer it's not a big cost. Considering above I started to think about changing my habit to use the first approach always for collections that I am sure that support moving (so most of STL collections). Second approach for custom objects (I assume that cost of considering writing custom move constructor for a class outstrips the profit of readability). Is there any best practice that covers that? What approach do you usually apply? Am I missing something in my justification?
Aucun commentaire:
Enregistrer un commentaire