将函数的返回值分配给引用 C++? [英] Assign return value from function to a reference c++?

查看:25
本文介绍了将函数的返回值分配给引用 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++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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