【发布时间】:2011-02-06 10:37:38
【问题描述】:
考虑以下我返回double& 和string& 的代码。它在双精度的情况下工作正常,但在字符串的情况下却不行。为什么行为不同?
在两种情况中,当我返回一个引用时,编译器甚至不会抛出Warning: returning address of local variable or temporary。
#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 =
【问题讨论】:
-
我有一个类似的帖子,那里的答案很有帮助。另外,请查看 cmets stackoverflow.com/questions/2612709/…