Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create std::string from char* in a safe way

Tags:

c++

exception

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?

like image 437
n-alexander Avatar asked Oct 29 '08 11:10

n-alexander


1 Answers

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.

like image 185
Chris Jester-Young Avatar answered Oct 28 '22 01:10

Chris Jester-Young