如果我在 C++11 中保留对函数的非引用返回值的常量引用,那么该引用指向堆栈中的哪里?这样做安全吗?
string foo() {
std::string foo_ret = "foo string";
return foo_ret;
}
int main() {
const std::string& a = foo();
}
Your code is illegal; non-const lvalue references may not bind to rvalues. There's not really a good reason behind this, it's just a language rule that was introduced very early on in C++'s history.
MSVC used to (maybe still does) allow this binding, I can't comment on how MSVC implements it.
不过,您可以绑定到其他引用类型:
std::string const &a = foo(); // (1)
std::string&& b = foo(); // (2)
在情况(2)中,b
直接绑定到返回值对象,该对象的生命周期已延长以匹配b
的一生。注意:这里没有发生“移动”操作,它只是绑定一个引用。
在情况 (1) 中,从概念上讲,是一个临时类型const std::string
从返回值初始化,并且该临时对象的生命周期已延长以匹配a
的一生。实际上,这个副本将是elided。您的代码的行为就像引用直接绑定到返回值一样。
一般来说,您应该使用值语义。std::string c = foo();
是最安全的选择。由于复制省略,它的效率并不比参考选项低。
引用选项的主要危险是,如果将函数更改为返回引用,则a
or b
可能会成为悬空参考。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)