Assign return value from function to a reference c++?(将函数的返回值分配给引用 C++?)
问题描述
这是一个两部分的问题.可以将函数的返回值分配给引用吗?比如
This is a two part question. Is it ok to assign the return value of a function to a reference? Such as
Foo FuncBar()
{
return Foo();
}
// some where else
Foo &myFoo = FuncBar();
这样好吗?我的理解是 FuncBar()
返回一个 Foo 对象,现在 myFoo
是对它的引用.
Is this ok? Its my understanding that FuncBar()
returns a Foo object and now myFoo
is a reference to it.
问题的第二部分.这是优化吗?因此,如果您经常在循环中执行此操作,最好这样做
Second part of the question. Is this an optimization? So if your doing it in a loop a lot of the time is it better to do
Foo &myFoo = FuncBar();
或
Foo myFoo = FuncBar();
考虑到变量的使用,使用 ref 会不会需要更慢的解引用?
And take into account the variables use, won't using the ref require slower dereferences?
推荐答案
Foo &myFoo = FuncBar();
不会编译.应该是:
const Foo &myFoo = FuncBar();
因为 FuncBar()
返回一个临时对象(即右值)并且只有左值可以绑定到对非常量的引用.
because FuncBar()
returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.
安全吗?
是的,它是安全的.
C++ 标准规定,将临时对象绑定到对 const 的引用可将临时对象的生命周期延长至引用本身的生命周期,从而避免常见的悬空引用错误.
C++ standard specifies that binding a temporary object to a reference to const lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error.
Foo myFoo = FuncBar();
是复制初始化.
它创建由 FuncBar()
返回的对象的副本,然后使用该副本来初始化 myFoo
.myFoo
是语句执行后一个单独的对象.
Is Copy Initialization.
It creates a copy of the object returned by FuncBar()
and then uses that copy to initalize myFoo
. myFoo
is an separate object after the statement is executed.
const Foo &myFoo = FuncBar();
将 FuncBar()
返回的临时对象绑定到引用 myFoo
,注意 myFoo
只是返回的临时对象的别名,而不是一个单独的对象.
Binds the temporary returned by FuncBar()
to the reference myFoo
, note that myFoo
is just an alias to the returned temporary and not a separate object.
这篇关于将函数的返回值分配给引用 C++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将函数的返回值分配给引用 C++?


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30