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

冷暖自知 提交于 2019-12-05 15:35:00
  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.

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.

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