Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Is it possible to detach the char* pointer from an std::string object?

I am using the std::string type for my string manipulations.

However, sometimes I need to keep the raw char* pointer, even after the original std::string object is destroyed (yes, I know the char* pointer references the HEAP and must eventually be disposed of).

However, looks like there is no way to detach the raw pointer from the string or is it?

Maybe I should use another string implementation?

Thanks.

EDIT

Folks, please do not confuse detaching with copying. The essence of detaching is for the string object to relinquish its ownership on the underlying buffer. So, had the string had the detach method, its semantics would be something like this:

char *ptr = NULL;
{
  std::string s = "Hello world!";
  ptr = s.detach(); // May actually allocate memory, if the string is small enough to have been held inside the static buffer found in std::string.
  assert(s == NULL);
}
// at this point s is destroyed
// ptr continues to point to a valid HEAP memory with the "Hello world!" string in it.
...
delete ptr; // need to cleanup
like image 431
mark Avatar asked Jan 02 '12 09:01

mark


1 Answers

No, it is not possible to detach the pointer returned by std::string::c_str().

Solution: Make a read-only copy of the string, and ensure that that copy lives at least as long as you need the char* pointer. Then use c_str() on that copy, and it will be valid as long as you want.

If that is not possible, then you won't be able to release the char* either. And any attempt to wrap that pointer in a RAII construction, will only re-invent parts of std::string.

like image 194
Sjoerd Avatar answered Nov 15 '22 04:11

Sjoerd