Return a move-only object from member function

时光毁灭记忆、已成空白 提交于 2019-12-11 10:21:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!