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.
Pass by value: not good in general as a value copy might be taken. (Although a move constructor might mitigate).
Pass by reference: not good as the function might modify the parameter passed. Also an anonymous temporary cannot bind to a reference.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With