【发布时间】:2013-09-10 15:05:27
【问题描述】:
有a set of good rules to determine whether pass by value or const reference
- 如果函数打算更改参数作为副作用,请采取 它通过非常量引用。
- 如果函数没有修改它的参数并且参数是 原始类型,按值取值。
- 否则通过 const 引用获取,但以下情况除外 案例:如果函数需要复制 const 无论如何参考,按价值取值。
如下构造函数,如何确定?
class A
{
public:
A(string str) : mStr(str) {} // here which is better,
// pass by value or const reference?
void setString(string str) { mStr = str; } // how about here?
private:
string mStr;
};
【问题讨论】:
-
构造函数平均比
mStr(std::move(str))更好。如果你真的需要进一步优化,你仍然可以重载它。 -
无论如何你都得拿一份,不是吗?
-
@chris 我认为您的
move方式也适用于setString。如果string没有 move ctor 和 assignment,哪种方式更好?谢谢。 -
是的,我没怎么看赋值运算符,但我想它会的。无论如何,我可能会说一个 const 引用。
标签: c++ parameter-passing