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.