正如标题所说:
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 firstsize()
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/