Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ how to create std::string containing size uninitialized bytes?

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

like image 513
hanshenrik Avatar asked Apr 23 '20 08:04

hanshenrik


People also ask

Is std::string initialized to empty?

A std::string isn't a pointer, so it shouldn't be combined. PS. the initializations are the same: the ctor of std::string sets it to the empty string.

How many bytes is a std::string?

Example. In below example for std::string::size. The size of str is 22 bytes.

Does std::string store size?

std::string actually maintains the size as one of its data member.


1 Answers

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);
like image 51
bartop Avatar answered Oct 18 '22 05:10

bartop