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

问题描述 投票:2回答:1

我需要一个size字节的std :: string,在构造它之后,我将在读取它之前写入该字符串中的每个字节,因此对字符串进行null初始化是对cpu的浪费,这是可行的:

std::string s(size,0);

但是它只是有点浪费,当我需要的全部是calloc()时,基本上就像使用malloc(),所以问题是,如何构造一个X个未初始化字节的字符串?

((使用reserve()+ push不能选择,因为我将字符串提供给使用char*,size进行实际初始化的C-api)

编辑:该线程似乎存在相同的问题/相关(但使用向量而不是字符串):Value-Initialized Objects in C++11 and std::vector constructor

c++ optimization std stdstring
1个回答
4
投票

std::string无法做到。但这可以通过不同的方式来实现,例如使用std::unique_ptr<char[]>

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

或者如果您的编译器支持C ++ 20

auto pseudo_string = std::make_unique_for_overwrite<char[]>(size);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.