gpt4 book ai didi

c++ - 保留然后分配给 std::string

转载 作者:搜寻专家 更新时间:2023-10-31 01:00:41 25 4
gpt4 key购买 nike

如果我调整大小然后分配一个 std::string 如下

std::string str;
str.resize(4);
str[1] = 'A'; // No problem

应该没有问题,但是如果我reserve然后assign

std::string str;
str.reserve(4);
str[1] = 'A'; // ?

会不会有问题?我读到元素未初始化并且大小没有增加。那么用 [] 运算符赋值给一个元素有意义吗?

最佳答案

来自 cplusplus

By reserving a capacity for the string of at least the size of the entire file, we try to avoid all the automatic reallocations that the object str could suffer each time that inserting a new character would make its length surpass its capacity.

reserve 不会增加字符串的大小,只是说明下次重新分配时需要增加多少。

关于c++ - 保留然后分配给 std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com