Efficient string constructor

c++, string

Solution

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

In C++11 you can have the temporary moved instead after passing by value:

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

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

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

Since only one user-defined conversion may apply implicitly, the `std::string` function won't receive a `String` argument by conversion through `char const *`. Note, however, that with an additional conversion function to `std::string` and both constructors, the result would be overload ambiguity.

Problem

Some classes I meet, have a dual string constructor: ``` construct( const std::string& s ); construct( const char* s ); ``` Having a `std::string` constructor has the obvious benefit of being able to pass a `std::string` without `c_str()`. However, if the argument is stored in a std::string anyway, is there any benefit of having 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 away? Additional question - does C++11 move construction change anything here?

Original source