问题描述
这是一个两部分的问题。是否可以将函数的返回值分配给引用?如
Foo FuncBar()
{
return Foo
}
//其他地方
Foo& myFoo = FuncBar();
这是否确定?我的理解是, FuncBar()
返回一个Foo对象,现在 myFoo
是对它的引用。
问题的第二部分。这是优化吗?所以如果你在一个循环中做很多时间是更好的做
Foo& myFoo = FuncBar ;
或
Foo myFoo = FuncBar();
并考虑到变量使用,不会使用ref需要更慢的解引用?
Foo& myFoo = FuncBar
无法编译。它应该是:
const Foo& myFoo = FuncBar
因为 FuncBar()
返回一个临时对象(即,rvalue),只有lvalues可以绑定到非const的引用。
b $ b
是安全的。
C ++标准规定将临时对象绑定到const的引用会延长临时对象的生命周期参考本身,因此避免了否则将是常见的悬挂 - 参考误差。
Foo myFoo = FuncBar
是复制初始化。
由 FuncBar()
返回的对象的副本,然后使用该副本初始化 myFoo
。 myFoo
是执行语句后的单独对象。
const Foo & myFoo = FuncBar();
绑定由 FuncBar()返回的临时
到参考 myFoo
,注意 myFoo
只是一个返回的临时的别名,而不是一个单独的对象。 p>
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();
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();
or
Foo myFoo = FuncBar();
And take into account the variables use, won't using the ref require slower dereferences?
Foo &myFoo = FuncBar();
Will not compile. it should be:
const Foo &myFoo = FuncBar();
because FuncBar()
returns a temporary object (i.e., rvalue) and only lvalues can be bound to references to non-const.
Yes it is safe.
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();
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();
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 ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!