<分区>
#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)
不会导致分配?
<分区>
#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 lengthn
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 lastsize() - n
elements.(5.2) If
n > size()
, appendsn - size()
copies ofc
.
关于c++ - 如果 new_size 不大于旧的,C++ 标准是否保证 std::string::resize(new_size) 不会导致分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57588615/