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?
#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 中,标准resize
constexpr
并且上述措辞消失了,请参阅 string.capacity:
constexpr void resize(size_type n, charT c);
5 #Effects:更改
*this
的值,如下所示:(5.1( 如果
n <= size()
,则删除最后size() - n
元素。(5.2( 如果
n > size()
,则附加c
的n - size()
副本。
它不保证指针的有效性:
引用basic_string序列元素的引用、指针和迭代器可能会因该basic_string对象的以下用法而失效:
作为参数传递给任何标准库函数,将对非常量basic_string的引用作为参数。
调用非常量成员函数,运算符 []、at 、data、front、back、begin、rbegin、end 和 rend 除外。
resize
是一个非 const 成员函数,不在保证不会使引用无效的成员函数列表中。
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 大于65535的C++数组[size]引发不一致的溢出
- 为什么(-1)%vector::size()总是返回0
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如果"new int"返回"int*",那么为什么"new int[n]"不返回"int**"?
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 重载运算符new[]的行为取决于析构函数
- 过载'operator new'如何导致无限循环?
- 创建具有 new in 函数和"this is nullptr"异常的对象
- Codelite C++ new project
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- 在类c++中使用new声明数组
- g++用户定义的动态链接库上的全局new和delete运算符
- 如果整个应用程序是虚拟映射的,为什么 new 会进行系统调用?
- C++ "new T[size]"不起作用?
- new int[size] vs std::vector
- 从(bad) array[size]移动到array = new float[size]
- 新增[size]对象(args ..)在数组new [-fpermissive]中添加圆括号初始化器
- 错误:数组new中的size必须是整型[-fpermissive]
- new(size, value) Type[0]返回的指针是否合法,是否可以用来构建数组?