在我维护的一个项目中,我看到很多简单的 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/