std::shared_ptr p;
};
std::string getWidgetName(); // factory function
Widget w;
auto n = getWidgetName(); // n is local variable
w.setName(n); // moves n into w!
… // n's value now unknown
Here, the local variable n
is passed to w.setName
, which the caller can be forgiven for assuming is a read-only operation on n. But because setName
internally uses std::move
to unconditionally cast its reference parameter to an rvalue, n
's value will be moved into w.name
, and n
will come back from the call to setName
with an unspecified value. That's the kind of behavior that can drive callers to despair — possibly to violence.
You might argue that setName
shouldn't have declared its parameter to be a universal reference. Such references can't be const
(see Item 24), yet setName
surely shouldn't modify its parameter. You might point out that if setName
had simply been overloaded for const
lvalues and for rvalues, the whole problem could have been avoided. Like this:
class Widget {
public:
void setName( const std::string&newName) // set from
{ name = newName; } // const lvalue
void setName(std::string&& newName) // set from
{ name = std::move(newName); } // rvalue
…
};
That would certainly work in this case, but there are drawbacks. First, it's more source code to write and maintain (two functions instead of a single template). Second, it can be less efficient. For example, consider this use of setName
:
w.setName("Adela Novak");
With the version of setName
taking a universal reference, the string literal "Adela Novak"
would be passed to setName
, where it would be conveyed to the assignment operator for the std::string
inside w
. w
's name
data member would thus be assigned directly from the string literal; no temporary std::string
objects would arise. With the overloaded versions of setName
, however, a temporary std::string
object would be created for setName
's parameter to bind to, and this temporary std::string
would then be moved into w
's data member. A call to setName
would thus entail execution of one std::string
constructor (to create the temporary), one std::string
move assignment operator (to move newName
into w.name
), and one std::string
destructor (to destroy the temporary). That's almost certainly a more expensive execution sequence than invoking only the std::string
assignment operator taking a const char*
pointer. The additional cost is likely to vary from implementation to implementation, and whether that cost is worth worrying about will vary from application to application and library to library, but the fact is that replacing a template taking a universal reference with a pair of functions overloaded on lvalue references and rvalue references is likely to incur a runtime cost in some cases. If we generalize the example such that Widget
's data member may be of an arbitrary type (rather than knowing that it's std::string
), the performance gap can widen considerably, because not all types are as cheap to move as std::string
(see Item 29).
The most serious problem with overloading on lvalues and rvalues, however, isn't the volume or idiomaticity of the source code, nor is it the code's runtime performance. It's the poor scalability of the design. Widget::setName
takes only one parameter, so only two overloads are necessary, but for functions taking more parameters, each of which could be an lvalue or an rvalue, the number of overloads grows geometrically: n
parameters necessitates 2 ⁿ
overloads. And that's not the worst of it. Some functions — function templates, actually — take an unlimited number of parameters, each of which could be an lvalue or rvalue. The poster children for such functions are std::make_shared
, and, as of C++14, std::make_unique
(see Item 21). Check out the declarations of their most commonly used overloads:
template // from C++11
shared_ptr make_shared( Args&&...args); // Standard
template // from C++14
unique_ptr make_unique( Args&&...args); // Standard
For functions like these, overloading on lvalues and rvalues is not an option: universal references are the only way to go. And inside such functions, I assure you, std::forward
is applied to the universal reference parameters when they're passed to other functions. Which is exactly what you should do.
Well, usually. Eventually. But not necessarily initially. In some cases, you'll want to use the object bound to an rvalue reference or a universal reference more than once in a single function, and you'll want to make sure that it's not moved from until you're otherwise done with it. In that case, you'll want to apply std::move
(for rvalue references) or std::forward
(for universal references) to only the final use of the reference. For example:
template // text is
void setSignText(T&& text) // univ. reference
{
sign.setText( text); // use text, but
// don't modify it
auto now = // get current time
std::chrono::system_clock::now();
signHistory.add(now,
std::forward( text)); // conditionally cast
} // text to rvalue
Here, we want to make sure that text's value doesn't get changed by sign.setText
, because we want to use that value when we call signHistory.add
. Ergo the use of std::forward
on only the final use of the universal reference.
For std::move
, the same thinking applies (i.e., apply std::move
to an rvalue reference the last time it's used), but it's important to note that in rare cases, you'll want to call std::move_if_noexcept
instead of std::move
. To learn when and why, consult Item 14.
If you're in a function that returns by value , and you're returning an object bound to an rvalue reference or a universal reference, you'll want to apply std::move
or std::forward
when you return the reference. To see why, consider an operator+
function to add two matrices together, where the left-hand matrix is known to be an rvalue (and can hence have its storage reused to hold the sum of the matrices):
Matrix // by-value return
operator+( Matrix&& lhs, const Matrix& rhs) {
lhs += rhs;
return std::move(lhs); // move lhs into
} // return value
By casting lhs
to an rvalue in the return
statement (via std::move
), lhs
will be moved into the function's return value location. If the call to std::move
were omitted,
Matrix // as above
operator+(Matrix&& lhs, const Matrix& rhs) {
Читать дальше