Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.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++_Visual Studio - Fatal编程技术网

C++ 左值引用绑定按值返回时崩溃?

C++ 左值引用绑定按值返回时崩溃?,c++,visual-studio,C++,Visual Studio,MSVC正在接受这个片段 #include <iostream> #include <string> #include <vector> std::string retstr() { return std::string("HelloWorld"); } void callFunc(std::string& ref) { std::cout << ref; } int main() { callFunc(ret

MSVC正在接受这个片段

#include <iostream>
#include <string>
#include <vector>

std::string retstr() {
 return std::string("HelloWorld");   
}

void callFunc(std::string& ref) {
 std::cout << ref;   
}

int main()
{
    callFunc(retstr());
}
#包括
#包括
#包括
std::string retstr(){
返回std::string(“HelloWorld”);
}
void callFunc(std::string和ref){

std::cout编写的代码在生命周期方面没有问题,因为临时值
retstr()
会一直存在到完整表达式的结尾,所以它的生命周期与函数调用的时间一样长


MSVC允许将左值引用绑定到右值的事实不会改变这一点。与往常一样,您必须确保
callFunc
不会在函数调用持续时间之后将引用存储到字符串中。

将非常量引用绑定到“右值”应该由编译器标记。但是,如果编译器没有标记它(如您的情况),它在运行时会有问题(也可能崩溃)

void callFunc(std::string&ref){

STD::它绝对不是标准的。正如你所说,它不是标准的,谁知道呢?但是它不应该。你可能必须检查程序集。如果这些调用跨越DLL边界,你可能会有一个DLL边界问题。@ SeBasaTyrl它们不是,它们在同一个C++外部DLL中,它有一个外部C接口并被C模块调用…叹气..真是一团糟..不太可能导致崩溃。它的行为应该与通过const引用然后丢弃constness的行为相同。使用VS2013更新4,它不会在我的PC上崩溃。我没有VS2015,所以我无法在那里尝试。你使用的是哪个版本的VS?临时版本不会“立即丢失”,它将一直存在到完整表达式(即分号)的结尾。我希望您阅读完整的文章。我的意思是,在特定的示例中,在callFunc()之前,temporary将丢失函数被调用。我希望这是有意义的。但是这不是真的。在你编写的代码中,直到调用<代码> Calfunc完成的临时生命。完全错了。你需要一本基本的C++书籍。请参考一些。
void callFunc(std::string& ref) {
 std::cout << ref;   //what to display?? if temporary is referenced. 
}

int main()
{
    callFunc(retstr()); //would return temporary which will be lost       immidiately.
}