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_ptrfrom C++11 or Boost:This uses a very specific feature of
shared_ptrnot available inauto_ptror anything else, namely the ability to specify a custom deleter; in this case, I’m usingfreeas the deleter.