是否有传递构造函数参数的首选方法?特别是如果这些构造函数参数用于初始化成员变量。构造函数传递的首选参数
一个简化的例子。
class Example
{
public:
Example(/*type-1*/ str, /*type-2*/ v):
m_str(str),
m_v(v)
{ }
/* other methods */
private:
std::string m_str;
std::complex<float> m_v;
};
选项为:
- 通过噪声值,然后
std::move
对象进入构件。 const&
,然后将参数复制到成员中。&&
,然后用该参数初始化该成员。
什么应该是我的默认/首选参数传递样式?
它是否因不同的参数类型而改变?
我的直觉说使用右值引用,但我不知道我明白所有的优点和缺点。
“&&,然后使用参数”'示例(std :: string && str):m_str(str){}'初始化成员将复制一次。只是为了说清楚。 –
@ R.MartinhoFernandes:编译器不会使用'std :: string'的移动构造函数吗?为什么它会喜欢复制而不是移动? 'std :: forward'会解决这个问题吗? –
因为指定的右值引用是左值。 '示例(std :: string && str):m_str(std :: move(str)){}'移动。 –