Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/142.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将字符串文字返回到C++;_C++_String - Fatal编程技术网

C++ 将字符串文字返回到C++;

C++ 将字符串文字返回到C++;,c++,string,C++,String,编译以下代码时,编译器发出警告warning:returning reference to temporary const string& example1() { return "Hello"; } 此代码甚至不编译: void example2(){ const string& str = "Hello"; } 这是有效的,因为我们知道一个文本字符串被编译器初始化为只读内存段 char* example3() { return "Hello"; }

编译以下代码时,编译器发出警告
warning:returning reference to temporary

const string& example1()
{
    return "Hello";
}
此代码甚至不编译:

void example2(){
    const string& str = "Hello";
}
这是有效的,因为我们知道一个文本字符串被编译器初始化为只读内存段

char* example3()
{
    return "Hello";
}
你能帮我理解编译方法
example1()
时幕后发生了什么吗

非常感谢你的帮助

返回“Hello”
创建一个临时的
std::string
,该字符串将在函数结束时删除。在这里,您将返回函数调用末尾不存在的
std::string
上的引用


为了解决这个问题,您可以将
example1()
的返回类型更改为
string
添加到Jerome的答案中,如果您只想要字符串的一个副本,也可以这样做:

const string& example1()
{
    static string example = "Hello";
    return example;
}

(现在,
example
是一个静态函数变量,也将存在于函数外部。)

由于该方法返回一个
std::string
,因此将从字符串文本创建一个临时的
std::string
。这个临时文件在函数作用域的末尾被销毁。example2对我来说运行良好。最好只使用
string
而不使用
const
。非常感谢Jerome和Zenith。但是,在example2()的情况下,为什么不创建临时字符串呢?