Reputation: 6424
I have to use a library function that allocates a bit of memory for a generated string and returns a char*
, with the expectation that the caller eventually free the memory with free()
.
// Example declaration of the library function:
char* foo();
// ...
// Example usage:
auto foo_str = foo();
// ...
free(foo_str);
Is it possible to construct a std::string
from this pointer, passing ownership of the memory to the string object so it will be freed when the string is destructed? I know I could implement my own wrapper that would give this RAII behavior, but I'm guessing this wheel has already been invented once.
Upvotes: 5
Views: 1426
Reputation: 984
You can construct a std::string from the char* pointer, but the std::string will allocate the char array itself. You will still need to free the char* returned by your library :
char* c = foo();
std::string foo_str( c );
free( c );
You can also create a function that ensure the deletion of the char* and return a std::string :
std::string char_to_string_with_free( const char* c )
{
std::string str( c );
free( c );
return str;
}
Upvotes: 1
Reputation: 302718
No, you cannot use string
for such a thing. string
always owns its buffer, and will allocate and deallocate its own. You can't transfer ownership into a string
. I don't even know if there's a proposal for such a thing.
There is a container that you can transfer ownership into though: unique_ptr
:
struct free_deleter {
void operator()(void* p) {
free(p);
}
};
std::unique_ptr<char, free_deleter> foo_str = foo();
Upvotes: 8
Reputation: 1827
AFAIK std::string hasn't such constructor, that takes ownership of char*
. Anyway its a bad idea to free memory outside of library, where it was allocated (if we speak about shared object or DLL).
Upvotes: 1