问题
I'm having a difficult time with understand + use move semantics in C++. I have an object Variable
implements move constructor and move assignment but no copy constructor and assignment. Generally copying a Variable
makes no sense and I want to prohibit copying explicitly.
class Variable {
public:
// ctod/dtor things
Variable(Variable&&);
Variable& operator =(Variable&&);
// ...
};
The question is what is correct way of returning a Variable
from a function?
Variable& UserObject::giveMeYourVariable() {
// Calculate parameters
Variable v(/* Some parameters */);
return v; // <=== warning: reference to local variable 'v' returned
}
In another code:
UserObject x* = new UserObject;
Variable v = std::move(x->giveMeYourVariable())
Above code compiles with no error but a warning about returning a reference to local variable. Does this code leaks memory or cause undefined behavior or return a deleted reference? What am doing wrong?
Update
Return by value causes error while initializing a reference type (inside a code that is generated by a parser-generator):
Variable& tmp (this->a_function()); <<== error
The error says:
error: invalid initialization of non-const reference of type 'Variable&' \\
from an rvalue of type 'Variable'
Update 2
This issue is reported in XSD mailing list and will be resolved in next release.
回答1:
Your program invokes undefined behavior.
As the compiler already told you, the lifetime of your Variable
object is limited to the function call and the reference you return is no longer valid after the call.
You can simply return your Variable
object by value
Variable UserObject::giveMeYourVariable() {
and happily move it around.
回答2:
You should move twice and return Variable object by value:
#include <utility>
class Variable {
public:
// ctod/dtor things
Variable() {}
Variable(Variable&&) {}
Variable& operator =(Variable&&) {return *this;}
// ...
};
Variable foo() {
Variable v;
return std::move(v);
}
int main() {
Variable v = std::move(foo());
return 0;
}
std::move just switch type from Variable to Variable&&, that allows to call constructor with move semantic
so:
first std::move allows to create temporary object for return
second std::mode allows to create Variable v
来源:https://stackoverflow.com/questions/18055266/return-a-move-only-object-from-member-function