const或ref或const ref或value作为setter函数的参数 [英] const or ref or const ref or value as an argument of setter function
问题描述
恒定性
class MyClass {
// ...
private:
std::string m_parameter;
// ...
}
传递值:
void MyClass::SetParameter(std::string parameter)
{
m_parameter = parameter;
}
通过引用:
void MyClass::SetParameter(std::string& parameter)
{
m_parameter = parameter;
}
通过常量引用:
void MyClass::SetParameter(const std::string& parameter)
{
m_parameter = parameter;
}
按常量传递值:
void MyClass::SetParameter(const std::string parameter)
{
m_parameter = parameter;
}
通过通用引用:
void MyClass::SetParameter(std::string&& parameter)
{
m_parameter = parameter;
}
Pass-by-const-universal-ref:
Pass-by-const-universal-ref:
void MyClass::SetParameter(const std::string&& parameter)
{
m_parameter = parameter;
}
哪个变体是最好的(可能就C ++ 11及其移动语义)?
Which variant is the best (possibly in terms of C++11 and its move semantics)?
PS。在某些情况下可能是函数的主体不正确。
PS. May be bodies of the functions is in some cases incorrect.
推荐答案
-
按值传递:通常不好,因为可能会复制值。 (尽管move构造函数可能会缓解)。
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.
通过 const
参考:仍然是最好的。不执行任何拷贝,函数无法修改参数,匿名临时变量可以绑定到 const
引用。
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.
传递& 变体:目前毫无意义,因为按照编写函数体的方式,没有移动语义。如果您写了
std :: move(m_parameter,parameter)
来代替赋值,那么在某些情况下这可能会胜过(3),编译器会选择更好。
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.
这篇关于const或ref或const ref或value作为setter函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!