I am working with a library which returns a dynamically allocated null-terminated character string
const char* dynamically_allocated_string();
so I am responsible for calling delete on the returned value later. My first instinct is to wrap the value in a unique_ptr so that all the memory management is done automatically:
std::unique_ptr<const char[]> ptr{dynamically_allocated_string()};
If I want to make a std::string from this, I could call the string constructor as
std::string{ptr.get()};
However, this makes a copy of the existing character string to construct the std::string. Is there a way to both
- Wrap a dynamically allocated character string with
std::stringsuch that the underlying array is automaticallydeleted when the string goes out of scope - Avoid copying the original character string during
std::string's construction
I am aware of string_view but it does not take ownership of the original character array.