从成员函数返回只移动对象 [英] Return a move-only object from member function
问题描述
我有一个困难的时候理解+使用移动语义在C + +。我有一个对象 Variable
实现移动构造函数和移动赋值,但没有复制构造函数和赋值。一般来说,复制变量
没有任何意义,我想禁止显式复制。
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
}
在另一个代码中:
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
错误说:
error: invalid initialization of non-const reference of type 'Variable&' \\
from an rvalue of type 'Variable'
更新2
此问题是在XSD邮件列表中报告,将会是已解决。
推荐答案
您的程序调用未定义的行为。
正如编译器已经告诉的, Variable
对象的生命周期仅限于函数调用并且您返回的引用在调用后不再有效。
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.
您可以简单地按
变量UserObject :: giveMeYourVariable(){
并快乐移动。
这篇关于从成员函数返回只移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!