保持对C ++中函数返回值的恒定引用 [英] Keep constant reference to return value of function in C++

查看:106
本文介绍了保持对C ++中函数返回值的恒定引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在C ++ 11中对函数的非引用返回值保持不变的引用,则引用在堆栈中的哪个位置?

If I keep a constant reference to a non-reference returned value of a function in C++11, where does the reference point in the stack? And is it safe to do so?

string foo() {
  std::string foo_ret = "foo string";
  return foo_ret;
}

int main() {
  const std::string& a = foo();
}


推荐答案

您的代码是非法的;非常量左值引用可能不会绑定到右值。这背后并没有真正的好的原因,这只是C ++历史上很早就引入的一种语言规则。

MSVC过去(也许现在)允许

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.

您可以绑定到其他引用类型,但是:

You can bind to other reference types though:

std::string const &a = foo();   // (1)
std::string&& b = foo();        // (2)

在情况(2)中, b 直接绑定到返回值对象,该对象的生存期已延长,以匹配 b 的生存期。注意:这里没有移动操作,它只是绑定引用。

In case (2), b binds directly to the return value object, which has its lifetime extended to match b's lifetime. Note: no "move" operation occurs here, it is just binding a reference.

在情况(1)中,概念上是类型为的临时类型const std :: string 从返回值初始化,并且该临时对象的生存期延长到与 a 的生存期匹配。实际上,此副本将被消除。您的代码的行为就像引用直接绑定到返回值一样。

In case (1), conceptually, a temporary of type const std::string is initialized from the return value, and that temporary has its lifetime extended to match a's lifetime. In practice this copy will be elided. your code will behave as if the reference bound directly to the return value.

通常来说,您应该使用值语义。 std :: string c = foo(); 是最安全的选择。由于使用了复制,它的效率也不比引用选项低。

Generally speaking, you should use value semantics. std::string c = foo(); is the safest option. Because of copy elision, it is not any less efficient than the reference options.

引用选项的主要危险在于,如果将函数更改为返回引用,那么 a b 可能成为悬挂的参考。

The main danger with the reference option is that if the function were changed to return a reference, then a or b may become a dangling reference.

这篇关于保持对C ++中函数返回值的恒定引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆