jim*_*iki 3 c++ pass-by-reference pass-by-value pass-by-const-reference
我希望freeFunct在它自己的对象副本a上做非const的东西.
假设freeFunct需要是一个自由函数,因为在实际代码中它需要许多不同的参数,从所有这些函数调用几个公共函数,并且没有必要使它成为任何类的非静态成员函数.
我想到了三种不同的宣告方式.
我觉得第三种解决方案更糟糕.
前两个有什么区别吗?
还有更好的东西吗?
void freeFunct1(A a){
a.doStuff();
}
void freeFunct2(const A& a){
A b = a;
b.doStuff();
}
/**users of freeFunct3 are expected
*to give a copy of their variable:
*{
* A b = a;
* freeFunct3(b);
*}
*/
void freeFunct3(A& a){
a.doStuff();
}
Run Code Online (Sandbox Code Playgroud)
第一个是最好的:它允许调用者选择是复制还是移动他的对象,因此如果调用者不需要保留副本,则可以更有效.
freeFunct1(a); // "a" is copied and not changed
freeFunct1(std::move(a)); // "a" is moved and perhaps changed
Run Code Online (Sandbox Code Playgroud)
第二个类似,但强制副本.
正如你所说,第三个更容易出错,因为调用者必须知道它会修改参数.