7

i need a std::string of size bytes, after constructing it i am going to write to every byte in that string prior to reading from it, thus null-initializing the string is a waste of cpu, this works:

std::string s(size,0); 

but it's just slightly wasteful, it's basically like using calloc() when all i need is malloc(), so the question is, how do i construct a string of X uninitialized bytes?

(using reserve()+push is not an option because im giving the string to a C-api taking char*,size to do the actual initialization)

edit: this thread seems to about the same issue/related (but with vectors instead of strings): Value-Initialized Objects in C++11 and std::vector constructor

2
  • If its about optimization, and only malloc() is efficient enough, why not use it? It is not like it`s forbidden. Commented Apr 23, 2020 at 8:13
  • Perhaps std::string isn't the correct choice here? Perhaps you should be using a plain array (possibly dynamically allocated) instead? You can always put it into a std::string (or std::string_view) later. Commented Apr 23, 2020 at 8:14

1 Answer 1

5

You can't do it with std::string. But it can be achieved different way, like using std::unique_ptr<char[]>.

auto pseudo_string = std::unique_ptr<char[]>(new char[size]); 

Or if your compiler supports C++20

auto pseudo_string = std::make_unique_for_overwrite<char[]>(size); 
Sign up to request clarification or add additional context in comments.

6 Comments

Wouldn't all the elements of the array be value-initialized by std::make_unique?
@songyuanyao take a look at your own link overload (2) and (5)
It appears a that c++20 introduces std::make_unique_for_overwrite to do just this.
@bartop ? Then shouldn't make_unique_for_overwrite be used instead?
- i tested the custom allocator theory, and no, even with a custom allocator, initialization of the string will be done by the string constructor post-allocation ( wandbox.org/permlink/HfH7wENQ0XuS61ye )
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.