C ++传递Const引用和返回由Const引用 [英] C++ Pass By Const Reference and Return By Const Reference

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

问题描述

我试图理解返回 const 引用是否有任何好处。我有一个阶乘函数,通常看起来像这样:

 无符号长阶乘(无符号长整数)
{
return(n == 0)? 1:n *阶乘(n-1);
}

我假设当我们传递 const 引用,我们返回一个 const 引用...但 const -correctness 总是困惑我。

  const unsigned long& factorial(const unsigned long& n)
{
return(n == 0)? 1:n *阶乘(n-1);
}

是否有效返回 const 参考?

解决方案

这是无效的。您不能返回对本地变量的引用。



MSVS C ++编译器甚至会发出以下警告:

  main.cc:warning C4172:返回局部变量或临时变量的地址
pre>

不太确定GCC,但结果可能是一样的。


I'm trying to understand if there is any benefit to returning a const reference. I have a factorial function that normally looks like this:

unsigned long factorial(unsigned long n)
{
    return (n == 0) ? 1 : n * factorial(n - 1);
}

I'm assuming that there will be a performance increase when we pass by const reference and we return a const reference... but const-correctness always confuses me.

const unsigned long & factorial(const unsigned long& n)
{
    return (n == 0) ? 1 : n * factorial(n - 1);
}

Is it valid to return a const reference? Furthermore, could somebody please tell me: is it beneficial?

解决方案

This is invalid. You can't return reference to a local variable.

MSVS C++ compiler even gives the following warning:

main.cc : warning C4172: returning address of local variable or temporary

Not quite sure about GCC, but probably the result would be the same.

这篇关于C ++传递Const引用和返回由Const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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