c++ - 如果新尺寸与旧尺寸相同,标准是否保证 std::string::resize 不会做任何事情?

标签 c++ string resize

正如标题所说:

Does the standard guarantee, that std::string::resize will not do anything, if the new size is the same as the old one?

当然可以测试,但可能是UB,所以这里测试不行。
在 cppreference.com 和 cplusplus.com 中,文档对这种情况只字未提

例子:

std::string s( "asd" );
// s.size() is 3
s.resize( 3 );    // will this affect **somehow** the string?

最佳答案

不,没有任何保证。实现可以将字符串重新分配到新缓冲区,以减少其 capacity() .

标准说:

Effects: Alters the length of the string designated by *this as follows:

— 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.

— If n > size(), the function replaces the string designated by *this with a string of length n whose first size() elements are a copy of the original string designated by *this, and whose remaining elements are all initialized to c.

关于c++ - 如果新尺寸与旧尺寸相同,标准是否保证 std::string::resize 不会做任何事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11393566/

相关文章:

java - Java中计数器的一系列字符串操作

Python tkinter : issues resizing frames

c++ - 如何使用 FillRect() 绘制子窗口?

占位符可以与 fgets 一起使用吗?

python-3.x - 从字符串中过滤用户名

PHP 显示缩小和调整大小的图像

css - 调整宽度时如何固定DIV高度?移动/桌面/PC 浏览器兼容

c++ - 使用 OpenCV 非自由库时 vector 未定义

c++ - 在 C++ 中覆盖 + 运算符时分配内存

c++ - STL 映射到自身?