简体   繁体   English

c++ 如何创建包含未初始化字节大小的 std::string?

[英]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:我需要一个size字节的std :: string,在构造它之后我将在读取它之前写入该字符串中的每个字节,因此对字符串进行空初始化是浪费cpu,这有效:

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?但这只是有点浪费,基本上就像在我只需要malloc() calloc()一样,所以问题是,我如何构造一串 X 未初始化字节?

(using reserve()+push is not an option because im giving the string to a C-api taking char*,size to do the actual initialization) (使用reserve()+push 不是一个选项,因为我将字符串提供给C-api 使用char*,size来进行实际初始化)

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编辑:这个线程似乎与相同的问题/相关(但使用向量而不是字符串): C++11 和 std::vector 构造函数中的值初始化对象

You can't do it with std::string .你不能用std::string做到这一点。 But it can be achieved different way, like using std::unique_ptr<char[]> .但它可以通过不同的方式实现,例如使用std::unique_ptr<char[]>

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

Or if your compiler supports C++20或者,如果您的编译器支持 C++20

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM