How can I preallocate and initialize the character sequence inside `std::basic_string`?

梦想的初衷 提交于 2019-12-10 19:31:17

问题


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.

来源:https://stackoverflow.com/questions/17601632/how-can-i-preallocate-and-initialize-the-character-sequence-inside-stdbasic-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!