I have a char* p, which points to a \0-terminated string. How do I create a C++ string from it in an exception-safe way?
Here is an unsafe version:
string foo()
{
  char *p = get_string();
  string str( p );
  free( p );
  return str;
}
An obvious solution would be to try-catch - any easier ways?
You can use shared_ptr from C++11 or Boost:
string
foo()
{
    shared_ptr<char> p(get_string(), &free);
    string str(p.get());
    return str;
}
This uses a very specific feature of shared_ptr not available in auto_ptr or anything else, namely the ability to specify a custom deleter; in this case, I'm using free as the deleter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With