c++ - 如果 new_size 不大于旧的,C++ 标准是否保证 std::string::resize(new_size) 不会导致分配?

标签 c++ string performance memory-management standards

#include <string>
#include <cassert>

int main()
{
    auto s = "hello"s;
    auto p = &s[0];

    s.resize(3);
    assert('h' == *p); // always ok?
}

如果 new_size 不大于旧的,C++ 标准是否保证 std::string::resize(new_size) 不会导致分配?

最佳答案

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

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

If n <= size(), the function replaces the string designated by *this with a string of length n whose elements are a copy of the initial elements of the original string designated by *this.

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


在 C++20 标准中 resize制作constexpr上面的写法不见了,见string.capacity :

constexpr void resize(size_type n, charT c);

5 #Effects: Alters the value of *this as follows:

(5.1) If n <= size(), erases the last size() - n elements.

(5.2) If n > size(), appends n - size() copies of c.

关于c++ - 如果 new_size 不大于旧的,C++ 标准是否保证 std::string::resize(new_size) 不会导致分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57588615/

相关文章:

php - 如何将其转换为数组?

python - 不使用库函数查找字符串中子字符串出现的次数

c - 为什么 Golang 比 ANSI C 快,我该如何优化我的解决方案?

c++ - 如何在目标文件中引用绝对符号?

c++ - 在C++模块化编程中,如何组装.cpp和.h文件?

c++ - DirectX 11.2 错误 : X3501: 'main' entry point not found

string - SSRS Reporting Services - 在某个单词处分割字符串

C++ vector.begin() 和 vector[0]

database - 使用复合主键元素的 SELECT 性能

python - 为什么 ruby​​ 1.9 比 python 2.7 和 3.2 快?