c++ - const 或 ref 或 const ref 或 value 作为 setter 函数的参数

标签 c++ c++11 parameter-passing

恒常性

class MyClass {
// ...
private:
    std::string m_parameter;
// ...
}

按值传递:

void MyClass::SetParameter(std::string parameter)
{
    m_parameter = parameter;
}

通过引用:

void MyClass::SetParameter(std::string& parameter)
{
    m_parameter = parameter;
}

通过常量引用:

void MyClass::SetParameter(const std::string& parameter)
{
    m_parameter = parameter;
}

按常量值传递:

void MyClass::SetParameter(const std::string parameter)
{
    m_parameter = parameter;
}

通用引用传递:

void MyClass::SetParameter(std::string&& parameter)
{
    m_parameter = parameter;
}

传递常量通用引用:

void MyClass::SetParameter(const std::string&& parameter)
{
    m_parameter = parameter;
}   

哪个变体最好(可能就 C++11 及其移动语义而言)?

附言。可能是函数体在某些情况下不正确。

最佳答案

  1. 按值传递:一般情况下不好,因为值拷贝可能会被采用。 (虽然移动构造函数可能会减轻)。

  2. 通过引用传递:不好,因为函数可能修改传递的参数。此外,匿名临时不能绑定(bind)到引用。

  3. 通过 const 引用:仍然是最好的。没有复制,函数不能修改参数,匿名临时变量可以绑定(bind)到 const 引用。

  4. 通过 && 变体传递:目前没有意义,因为在您编写函数体的方式中没有移动语义。如果您编写了 std::move(m_parameter, parameter) 来代替赋值,那么在某些情况下这可能会胜过 (3),并且编译器会选择更好的。

关于c++ - const 或 ref 或 const ref 或 value 作为 setter 函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31402796/

相关文章:

c++ - 将 32 位地址的类型转换为 (BYTE *) 和 (DWORD *) 有什么区别

c++ - mongo-cxx-driver - 新的 C++11 驱动程序 - 如何从二进制数据创建文档

C++ 在运行时从编译时已知集/枚举中选择模板非类型参数

c++ - 确定 if::std::numeric_limits<T> 是否可以安全实例化

c++ - template模板类的param怎么取

c++ - VC++ 2010 中的 "moveable-only types"问题

c++ - 如何创建一个 vector 作为参数

php - 如何在表单提交时保留已设置的 GET 参数值?

variables - LESS:将带有变量的规则集(或 mixin)传递给另一个 mixin 并能够使用这些变量

android - 如何在自定义 ImageView 中将 R.Drawable 作为参数传递