Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 600
vladon Avatar asked Jul 14 '15 09:07

vladon


2 Answers

  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.

like image 127
Bathsheba Avatar answered Sep 28 '22 07:09

Bathsheba


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.

like image 29
Ed James Avatar answered Sep 28 '22 08:09

Ed James