<p>I have a <code>char* p</code>, which points to a <code>\0</code>-terminated string. How do I create a C++ <code>string</code> from it in an exception-safe way?</p>

<p>Here is an unsafe version:</p>

<pre><code>string foo()
{
  char *p = get_string();

  string str( p );
  free( p );
  return str;
}
</code></pre>

<p>An obvious solution would be to try-catch - any easier ways? </p>

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.