c++ - 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 best (possibly in terms of c++11 , move semantics)?
ps. may bodies of functions in cases incorrect.
pass value: not in general value copy might taken. (although move constructor might mitigate).
pass reference: not function might modify parameter passed. anonymous temporary cannot bind reference.
pass
const
reference: still best. no copy taken, function cannot modify parameter, , anonymous temporary can bindconst
reference.passing
&&
variants: pointless, there no move semantics given way you've written function bodies. if you'd writtenstd::move(m_parameter, parameter)
in place of assignment might win on (3) in cases, , compiler pick better.
Comments
Post a Comment