Effective String Designer

Some classes that I meet have a constructor with two lines:

construct( const std::string& s ); construct( const char* s ); 

The presence of the std::string constructor has an obvious advantage: pass std::string without c_str() . However, if the argument is stored in std :: string anyway, is there any use for the const char* constructor?

In particular:

  construct( const std::string& s ) : m_string( s ) {} construct( const char* s ) : m_string( s ) {} std::string m_string; 

Will the second constructor be faster for string literals and char* variables, or will it be optimized?

An additional question is - can C ++ 11 change the design of something here?

+7
c ++ string
source share
2 answers

In C ++ 03 or C ++ 11 without specifying the semantics of movement, the implicit conversion const char * to std::string creates a temporary string, which is then copied to the member. This implements an extra copy.

In C ++ 11, instead of an intermediate value, you can move the temporary code:

 construct( std::string s ) : member( std::move( s ) ) {} 

The only thing I can think of is compatibility with other classes that provide conversion operators.

 struct String { operator char const * () const; }; 

Since only one user-defined conversion can be applied implicitly, the std::string function will not receive a String argument by converting via char const * . Note, however, that with the extra conversion function to std::string and both constructors, the result will be an overload error.

+8
source share

If you have only char* and only the first constructor, a copy can be made 2 times. in std::string(char*) and in construct(std::string)

So far in the second constructor pointer will be copied (it is fast) and then copied.

In C ++ 11, a good idea is to create 1 constructor

  construct(std::string s ) : m_string( std::move(s) ) {} 

In this case, if you only have char* data can be copied to the ctor string, but the string will be temporary, so it will just be moved to construct ctor

This code prints "create, copy"
This code prints "create, move"

+5
source share

All Articles