左值引用绑定返回值的崩溃? [英] Crash for lvalue reference binding to return-by-value?
问题描述
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());
}
。
现在..我在DLL中的一些崩溃在一个函数,其工作原理与上面的这段代码:编译器没有警告我有一个左值引用绑定到一个ret-by-value thingy。
Now.. I'm getting some crashes in a DLL in a function which works exactly like this snippet above: the compiler didn't warn me of having a lvalue reference binding to a ret-by-value thingy.
我的问题是:这可能不是标准的,但是会导致程序崩溃(访问冲突是精确的)。
My question is: this is probably not standard but could it cause a program crash (access violation to be precise)?
推荐答案
所写的代码在生命周期很好,因为临时值 retstr()
- 表达式,所以它只要函数调用就可以生存。
The code as written is fine regarding lifetimes, since the temporary value retstr()
lives until the end of the full-expression, so it lives as long as the function call.
MSVC允许将左值引用绑定到右值的事实不会改变。一如既往,你必须确保 callFunc
在函数调用的持续时间之外不会将引用存储到字符串中。
The fact that MSVC allows binding a lvalue reference to an rvalue does not change that. As always, you have to make sure that callFunc
does not store references into the string beyond the duration of the function call.
这篇关于左值引用绑定返回值的崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!