简体   繁体   中英

Preferred parameter passing for constructors

Is there a preferred practice for passing constructor parameters? In particular if those constructor parameters are used to initialize member variables.

A simplified example.

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

The options are:

  • pass-by-value, then std::move the object into the member.
  • const& , then copy the parameter into the member.
  • && , then initialize the member with the parameter.

What should be my default/preferred parameter passing style?
Does it change with different parameter types?

My intuition says use rvalue-references, but I'm not sure I understand all the pros and cons.

Option 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;
};

This has pretty good performance and is easy to code. The one place it falls a little short of the optimum is when you bind an lvalue to str . In this case you execute both a copy construction and a move construction. The optimum is only a copy construction. Note though that a move construction for a std::string should be very fast. So I would start with this.

However if you really need to pull the last cycles out of this for performance you can do:

Option 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;
};

The main disadvantage of this option is having to overload/replicate the constructor logic. Indeed this formula will become unrealistic if you have more than one or two parameters that you need to overload between const& and && .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM