Two constructors are needed because you can pass a NULL
to your MyClass::MyClass(const std::string &arg)
. Providing second constructor saves you from a silly crash.
For example, you write constructor for your class, and make it take a const std::string &
so that you don't have to check any pointers to be valid if you'd be using const char*
.
And everywhere in your code you're just using std::string
s. At some point you (or another programmer) pass there a const char*
. Here comes nice part of std::string
- it has a constructor, which takes char*
, and that's very good, apart from the fact, that std::string a_string(NULL)
compiles without any problems, just doesn't work.
That's where a second constructor like you've shown comes handy:
MyClass::MyClass(const char* arg)
: m_string(arg ? arg : "")
{}
and it will make a valid std::string
object if you pass it a NULL
.
In this case I don't think you'd need to worry about any speed. You could try measuring, although I'm afraid you'd be surprised with how little difference (if any) there would be.
EDIT: Just tried std::string a_string(NULL);
, compiles just fine, and here's what happens when it is run on my machine (OS X + gcc 4.2.1) (I do recall I tried it on Windows some time ago, result was very similar if not exactly same):
std::logic_error: basic_string::_S_construct NULL not valid