将const引用传递给原始类型有什么用? [英] What is the use of passing const references to primitive types?

查看:79
本文介绍了将const引用传递给原始类型有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我维护的项目中,我看到了很多类似这样的代码,它们用于简单的 get / set 方法

In a project I maintain, I see a lot of code like this for simple get/set methods

const int & MyClass::getFoo() { return m_foo; }

void MyClass::setFoo(const int & foo) { m_foo = foo; }

这样做不是什么意思?

int MyClass::getFoo() { return m_foo; }  // Removed 'const' and '&' 

void MyClass::setFoo(const int foo) { m_foo = foo; }  // Removed '&'

将引用传递给原始类型应要求相同(或

毕竟只是一个数字...

这只是一些尝试过的微优化还是有真正的好处?

Passing a reference to a primitive type should require the same (or more) effort as passing the type's value itself, right?
It's just a number after all...
Is this just some attempted micro-optimization or is there a true benefit?

推荐答案

不同之处在于,如果您自己将结果获取到引用中,则可以跟踪整数变量在您的变量中的变化自己的变量名,而无需调用该函数。

The difference is that if you get that result into a reference yourself you can track the changes of the integer member variable in your own variable name without recalling the function.

const &int x = myObject.getFoo();
cout<<x<<endl;
//...
cout<<x<<endl;//x might have changed

这可能不是最佳的设计选择,并且如果返回的变量从作用域中释放出来,则返回一个引用(是否为const)是非常危险的。因此,如果返回引用,请务必确保它不是超出范围的变量。

It's probably not the best design choice, and it's very dangerous to return a reference (const or not), in case a variable that gets freed from scope is returned. So if you return a reference, be careful to be sure it is not a variable that goes out of scope.

修饰符也有细微差别,但同样

There is a slight difference for the modifier too, but again probably not something that is worth doing or that was intended.

void test1(int x)
{
  cout<<x<<endl;//prints 1
}

void test2(const int &x)
{
  cout<<x<<endl;//prints 1 or something else possibly, another thread could have changed x
}

int main(int argc, char**argv)
{
  int x = 1;
  test1(x);
  //...
  test2(x);
  return 0;
}

因此,最终结果是即使传递了参数,您也可以获得更改。

So the end result is that you obtain changes even after the parameters are passed.

这篇关于将const引用传递给原始类型有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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