title: In C++, how can a class take a const std::string& parameter in the constructor but also handle NULL?
body: <p>I'm trying to work through ways to create a class with a std::string argument, but which also handles NULL without throwing an exception.  Here's an example of the code:</p>
  
  <pre><code>class myString {
  public:
      myString(const std::string&amp; str) : _str(str) {}
      std::string _str;
  };
  
  int main() {
      myString mystr(NULL);
      printf("mystr = &lt;%s&gt;\n", mystr._str.c_str());
      return 0;
  }
  </code></pre>
  
  <p>Intuitively, you'd think that this program should print "mystr = &lt;>" and exit successfully, but instead with g++ it gives this error:</p>
  
  <pre><code>terminate called after throwing an instance of 'std::logic_error'  
  what():  basic_string::_S_construct NULL not valid
  </code></pre>
  
  <p>How can I change this class so that it translates NULL into "" instead of throwing a logic_error exception?</p>
  
  <p>(Postscript: As you'd suspect, the "real" implementation is a bit more complicated than this example, having several arguments in the constructor and doing more interesting things with _str -- and properly keeping it private.  The motivation behind this example is that programmers in our team will tend to use NULL in this context for historical purposes, and the compiler won't catch this.  Retraining everyone to always use "" is relatively hard.  Alternatively, a clever solution would be easy)</p>