const or ref or const ref or value as an argument of setter function

旧时模样 提交于 2020-01-02 06:13:15

问题


Constantness

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

Pass-by-value:

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

Pass-by-ref:

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

Pass-by-const-ref:

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

Pass-by-const-value:

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

Pass-by-universal-ref:

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

Pass-by-const-universal-ref:

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

Which variant is the best (possibly in terms of C++11 and its move semantics)?

PS. May be bodies of the functions is in some cases incorrect.


回答1:


  1. Pass by value: not good in general as a value copy might be taken. (Although a move constructor might mitigate).

  2. Pass by reference: not good as the function might modify the parameter passed. Also an anonymous temporary cannot bind to a reference.

  3. Pass by const reference: still the best. No copy taken, function cannot modify the parameter, and an anonymous temporary can bind to a const reference.

  4. Passing by && variants: Currently pointless, as there are no move semantics given the way you've written the function bodies. If you'd written std::move(m_parameter, parameter) in place of the assignment then this might win over (3) in some cases, and the compiler will pick the better.




回答2:


See 'Effective C++' Scott Meyers - If the private member is a built in type then it can be more efficient to pass by value than pass by reference (which are typically implemented as pointers in the compiler). This is also true for iterators and function objects in STL which are designed to be passed by value. Otherwise pass by reference-to-const is preferable.



来源:https://stackoverflow.com/questions/31402796/const-or-ref-or-const-ref-or-value-as-an-argument-of-setter-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!