C++标准是否保证 std::string::resize(new_size) 在new_size不大于旧标准时不会导致

Does the C++ standard guarantee that std::string::resize(new_size) will not cause allocation if the new_size is not greater than the old one?

本文关键字:size new 不大于 标准时 标准 string std resize 是否 C++      更新时间:2023-10-16
#include <string>
#include <cassert>
int main()
{
auto s = "hello"s;
auto p = &s[0];
s.resize(3);
assert('h' == *p); // always ok?
}

C++标准是否保证new_size不大于旧标准时std::string::resize(new_size)不会造成分配?

首先请注意,标准通常设定要求而不是保证。

如果参数小于其当前size()resize则不需要std::basic_string::resize不重新分配字符串。事实上,C++17 标准说当前字符串被新字符串替换:

如果n <= size(),该函数将*this指定的字符串替换为长度为n的字符串 其元素是*this指定的原始字符串的初始元素的副本。

使用小字符串优化时,调整为较小的大小可能会导致字符串就地存储字符,而不是存储在动态分配的缓冲区中。


在 C++20 中,标准resizeconstexpr并且上述措辞消失了,请参阅 string.capacity:

constexpr void resize(size_type n, charT c);

5 #Effects:更改*this的值,如下所示:

(5.1( 如果n <= size(),则删除最后size() - n元素。

(5.2( 如果n > size(),则附加cn - size()副本。

它不保证指针的有效性:

引用

basic_string序列元素的引用、指针和迭代器可能会因该basic_string对象的以下用法而失效:

  • 作为参数传递给任何标准库函数,将对非常量basic_string的引用作为参数。

  • 调用非常量成员函数,运算符 []、at 、data、front、back、begin、rbegin、end 和 rend 除外。

resize是一个非 const 成员函数,不在保证不会使引用无效的成员函数列表中。