在C ++中返回引用 [英] Returning a reference in C++

查看:146
本文介绍了在C ++中返回引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码,其中返回 double& string& 。它在double的情况下工作正常,但不是在字符串的情况下。为什么行为不同?

Consider the following code where I am returning double& and a string&. It works fine in the case of a double but not in the case of a string. Why does the behavior differ?

两种情况下,编译器甚至不会抛出警告:

In both cases the compiler does not even throw the Warning: returning address of local variable or temporary as I am returning a reference.

#include <iostream>
#include <string>
using namespace std;


double &getDouble(){
    double h = 46.5;
    double &refD = h;
    return refD;
}

string &getString(){
    string str = "Devil Jin";
    string &refStr = str;
    return refStr;
}

int main(){
    double d = getDouble();
    cout << "Double = " << d << endl;

    string str = getString();
    cout << "String = " << str.c_str() << endl;

    return 0;
}




输出:



$ ./a.exe
Double = 46.5
String =


推荐答案

无论编译器做什么或不做。编译器可能很容易被欺骗。你不应该将你的代码的正确性基于一些可能没有被触发的警告。

You should never return a reference to a local variable no matter what the compiler does or does not do. The compiler may be fooled easily. you should not base the correctness of your code on some warning which may not have fired.

这里没有触发的原因可能是你不是字面上返回对本地变量的引用,您返回的变量是对本地变量的引用。编译器可能没有检测到这种更复杂的情况。它只检测以下内容:

The reason it didn't fire here is probably that you're not literally returning a reference to a local variable, you are returning a variable that is a reference to a local variable. The compiler probably doesn't detect this somewhat more complex situation. It only detects things like:

string &getString(){
    string str = "Devil Jin";
    return str;
}

double的情况更简单,因为它不涉及构造和破坏一个复杂的对象,所以在这种情况下,编译器的流控制分析可能在检测错误方面做得更好。

The case of the double is simpler because it doesn't involve constructing and destructing a complex object so in this situation the flow control analysis of the compiler probably did a better job at detecting the mistake.

这篇关于在C ++中返回引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆