C++ constructors and implicit string conversion
You'd need to overload your constructors if you wished to handle a C-string and an std::string
differently.
MyStringClass::MyStringClass( const std::string &str )
{
// Do std::string-specific stuff here.
}
MyStringClass::MyStringClass(const char * str )
{
// Do char* specific stuff here.
}
There's also the possibility that a parameter of const char *
is not a null-terminated C-string, but in fact a pointer to a single character, or a non-null-terminated character array. In this case, an implicit conversion might fail.
Example:
#include <iostream>
int DoStuff(const std::string &myString)
{
std::cout << myString << std::endl;
}
int main()
{
DoStuff("This is a null terminated c-string"); // Fine!
char charArray[] = { 'A', 'B', 'C' }; // Not null terminated!
DoStuff(charArray); // Uh oh!
}
The example above is for a function, but the same could be applied to a constructor too. The above example compiles without warnings!
In terms of performance, there is certainly a hit due to the fact that an std::string(const char * const)
constructor will copy the c-string into it's own internal buffer. However in most cases the impact will be negligible since the copy is extremely efficient. With very large strings however, it could be an issue.
As a general rule though, try to work with C++ strings as much as possible, and use the std::string::c_str()
member when C-style strings are required. The occasional string copy from char*
to std::string
will be a micro-optimization in most cases. Only in very performance-critical code would this be a potential concern.