excerpt from EMC++
This means that if you use std::move on a local object being returned from a function that’s returning by value, you can’t help your compilers (they have to treat the local object as an rvalue if they don’t perform copy elision), but you can certainly hinder them (by precluding the RVO).
There are situations where applying std::move to a local variable can be a reasonable thing to do (i.e., when you’re passing it to a function and you know you won’t be using the variable any longer), but as part of a return statement that would otherwise qualify for the RVO or that returns a by value parameter isn’t among them.
Widget makeWidget() // as before { Widget w; … return w; }compilers must either elide the copying of w or they must treat the function as if it were written like this:
Widget makeWidget() { Widget w; … return std::move(w); // treat w as rvalue, because } // no copy elision was performedThe situation is similar for by-value function parameters. They’re not eligible for copy elision with respect to their function’s return value, but compilers must treat them as rvalues if they’re returned. As a result, if your source code looks like this,
Widget makeWidget(Widget w) // by-value parameter of same { // type as function's return … return w; }compilers must treat it as if it had been written this way:
Widget makeWidget(Widget w) { … return std::move(w); // treat w as rvalue }
This means that if you use std::move on a local object being returned from a function that’s returning by value, you can’t help your compilers (they have to treat the local object as an rvalue if they don’t perform copy elision), but you can certainly hinder them (by precluding the RVO).
There are situations where applying std::move to a local variable can be a reasonable thing to do (i.e., when you’re passing it to a function and you know you won’t be using the variable any longer), but as part of a return statement that would otherwise qualify for the RVO or that returns a by value parameter isn’t among them.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.