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.

  1. pass value: not in general value copy might taken. (although move constructor might mitigate).

  2. pass reference: not function might modify parameter passed. anonymous temporary cannot bind reference.

  3. pass const reference: still best. no copy taken, function cannot modify parameter, , anonymous temporary can bind const reference.

  4. passing && variants: pointless, there no move semantics given way you've written function bodies. if you'd written std::move(m_parameter, parameter) in place of assignment might win on (3) in cases, , compiler pick better.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -