我有一个函数返回对我的类“record”实例的引用。
record& get_record(int key) {
return lookup(key);
}
这是有效的,它返回一个引用而不是按值。现在我稍微修改一下。
record& get_record(int key) {
if (valid(key))
return lookup(key);
else {
record x;
x.valid=false;
return x; //Here I really want to return a temporary variable
// and not a reference to a local variable.
}
}
返回对局部变量的引用不是一个好主意是否正确?以及如何以使其成为临时变量的方式返回 x ?
最佳答案
Is it correct that returning a reference to a local variable is not a good idea?
是的。退出函数时本地对象将被销毁,因此返回的引用始终悬空。
您可以将x
设为static
变量。
record& get_record(int key) {
if (valid(key))
return lookup(key);
else {
static record x;
x.valid=false;
return x;
}
}
请注意,返回的引用将始终引用同一对象,即 x
。
关于c++ - 如何在 C++ 中创建临时变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524160/