create std::string from char* in a safe way
c++, exception
Solution
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.
Problem
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?