2

是否有传递构造函数参数的首选做法?特别是如果这些构造函数参数用于初始化成员变量。

一个简化的例子。

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&,然后将参数复制到成员中。
  • &&,然后用参数初始化成员。

我的默认/首选参数传递方式应该是什么?
它会随着不同的参数类型而变化吗?

我的直觉说使用右值引用,但我不确定我是否理解所有的利弊。

4

1 回答 1

6

选项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;
};

这具有相当好的性能并且易于编码。当您将左值绑定到str. 在这种情况下,您将执行复制构造和移动构造。最优只是一个复制结构。请注意,a 的移动构造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&和之间重载多个参数,则此公式将变得不切实际&&

于 2011-10-04T16:14:37.420 回答