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

标签 c++ reference temporary

我有一个函数返回对我的类“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/

相关文章:

C++ STL 数据结构常量时间推送/弹出/通过索引随机访问元素的可靠指针

c++ - 如何强制不修改引用变量的任何部分?

c++ - 我想在基于 MFC 对话框的对话框中显示一些内容,但它在我的主对话框中没有显示任何内容!

java - 将对象添加到 ArrayList 而不引用

c++ - 当主应用程序处于 while 循环时,boost 线程未运行

c++ - 在 C++ 中使用 const 引用参数访问函数成员的最佳实践

rust - 可变引用的再借用

PHP/MySQL : Insert rows temporarily

c++ - 将临时对象传递给 std::cout

c++ - 对临时的常量引用