I am wondering how I could preallocate and initialize the character sequence inside an ordinary C++ string. The occasion for the question is querying the Windows registry for values. See this answer for some example code. The trouble is that the system call writes into an array allocated by the caller. I've already solved the immediate problem with an allocated buffer, but this solution has what seems to be an extraneous string copy. This got me curious about the general question, one more geared at library authors, about how one could eliminate the extra operation.
The constructors for std::basic_string
don't include an obvious way of doing this. In many ways I'd like to have a string constructor with a std::unique_ptr
argument that absorbs the allocation behind the pointer as its internal storage. I'm thinking of something like this sample code:
size_t len;
// ... Determine len
std::string::allocator_type a = std::string::allocator_type();
std::unique_ptr< char_t[] > p( a.allocate( len ) );
// ... Copy characters to p
std::string s( p, len, a ); // constant-time constructor
This doesn't work because there's no such constructor. The question is about how one might implement such a constructor.
It seems that the right way is to define a custom allocator whose allocate
function returns the pre-allocated storage and does so only once. Presumably this class would itself be generic, instantiated with the string allocator (like in the example). This seems like it would work, but I'm sure I don't understand all the ramifications of that approach.