c++ - 将 const 引用传递给原始类型有什么用?

标签 c++ reference constants primitive

在我维护的一个项目中,我看到很多简单的 get/set 方法的代码

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 '&'

传递对原始类型的引用应该需要与传递类型的值本身相同(或更多)的工作,对吧?
毕竟只是一个数字……
这只是一些尝试的微优化还是有真正的好处?

最佳答案

不同之处在于,如果您自己将该结果放入引用中,您可以在您自己的变量名中跟踪整数成员变量的更改,而无需调用函数。

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

这可能不是最好的设计选择,并且返回引用(无论是否为 const)非常危险,以防返回从范围中释放的变量。因此,如果您返回一个引用,请注意确保它不是超出范围的变量。

修饰符也有细微差别,但同样可能不是值得做的事情或预期的事情。

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;
}

所以最终的结果是,即使在参数传递之后,你也获得了变化。

关于c++ - 将 const 引用传递给原始类型有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/672700/

相关文章:

c 使用静态变量查找数字的倍数?

c++ const 类引用?

C++ : Dynamic C-String Usage in ifstreamObject. getline(c 字符串,字符限制)

尝试从 JAR 访问 XML 文件时出现 java.io.IOException : Stream closed,

c++ - std::vector<T>::resize 等价于 swift

c++ - 此 C++ 代码是否正确(从枚举标识符创建引用)?

constants - 将 ⊤ ("down tack") 字符定义为我可以在我的程序中使用的常量

c++ - "const& X"是什么意思,其中 X 是方法原型(prototype)中的结构?

c++ - OpenMP C++ : Load imbalance with parallelised for loop

c++ - 如何声明自引用模板类型