是否有传递构造函数参数的首选做法?特别是,如果使用这些构造函数参数初始化成员变量。
一个简化的例子。
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;
};备选方案如下:
然后
const&,中,然后将参数复制到member.&&,中,然后使用参数.初始化成员。
我的默认/首选参数传递样式应该是什么?
它会随着不同的参数类型而变化吗?
我的直觉说,使用rvalue-引用,但我不确定我是否理解所有的利弊。
发布于 2011-10-04 16:14:37
选项1:
class Example
{
public:
Example( std::string str, const std::complex<float>& v ):
m_str( std::move(str) ),
m_v( v )
{ }
/* other methods */
private:
std::string m_str;
std::complex<float> m_v;
};这具有相当好的性能和易于编码。当您将lvalue绑定到str时,它有一点不太理想。在这种情况下,可以同时执行副本构造和移动构造。最优不过是复制结构。不过,请注意,std::string的移动构造应该非常快。所以我先从这个开始。
但是,如果您确实需要将最后一个周期从这个循环中提取出来以获得性能,则可以这样做:
备选方案2:
class Example
{
public:
Example( const std::string& str, const std::complex<float>& v ):
m_str( str ),
m_v( v )
{ }
Example( std::string&& str, const std::complex<float>& v ):
m_str( std::move(str) ),
m_v( v )
{ }
/* other methods */
private:
std::string m_str;
std::complex<float> m_v;
};此选项的主要缺点是必须重载/复制构造函数逻辑。实际上,如果您需要在const&和&&之间重载一个或两个以上的参数,那么这个公式将变得不现实。
https://stackoverflow.com/questions/7650769
复制相似问题