小编use*_*458的帖子

如何在C++中创建临时变量

我有一个函数返回对我的类"记录"的实例的引用.

record& get_record(int key) {
    return lookup(key);
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,它返回一个引用而不是值.现在我稍微修改一下.

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.      
    }
}
Run Code Online (Sandbox Code Playgroud)

返回对局部变量的引用不是一个好主意是否正确?以及如何以一种临时变量的方式返回x?

c++ reference temporary

4
推荐指数
2
解决办法
1816
查看次数

标签 统计

c++ ×1

reference ×1

temporary ×1