1

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

  1. Wrap a dynamically allocated character string with std::string such that the underlying array is automatically deleted when the string goes out of scope
  2. 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.

1 Answer 1

3

There is no interface in std::string to take ownership of externally allocated buffers, unfortunately.

One option is to provide an oversized std::string buffer to the function that fills the buffer (if there is such an interface) and then trim that string to the actual size.

Otherwise, if you'd like to stick with std:: components and avoid allocating/copying the string your best choice is std::unique_ptr<const char[]> (may be with a custom deleter that matches the allocation function) converted into std::string_view on demand, as you mention in your question.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.