我正在阅读 std::basic_string::reserve(size_type res_arg=0)
上的标准.它是这样说的:
void reserve(size_type res_arg=0);
The member function reserve()
is a directive that informs a basic_string
object of a planned change in size, so that it can manage the storage allocation accordingly.
Effects: After reserve()
, capacity()
is greater or equal to the argument of reserve. [ Note: Calling reserve()
with a res_arg argument less than capacity()
is in effect a non-binding shrink request. A call with res_arg <= size()
is in effect a non-binding shrink-to-fit request. — end note ]
Throws: length_error if res_arg > max_size()
标准似乎在调用 reserve()
之间做出区分。其中 res_arg < capacity()
并调用 reserve()
TRONG res_arg <= size()
.
res_arg <= size()
很容易理解,shrink_to_fit()
被调用并且实现可以自由地做任何它想做的事情,因为它是非绑定(bind)的。
Nhưng res_arg < capacity()
的情况呢? ?该标准说的是“非约束性收缩请求”而不是“非约束性收缩至适合请求”。收缩至合身请求和收缩请求之间有什么区别?这只是一个不幸的不一致吗?
std::string::shrink_to_fit()
会将 capacity()
缩小到 size()
。这与将 capacity()
缩小到小于 capacity()
但大于 size()
的数字不同。生效
std:string foo = "test";
foo.reserve(20); // capaicty:20 size:4
foo.reserve(10); // capaicty:10 size:4
foo.reserve(20); // capaicty:20 size:4
foo.shrink_to_fit(); // capaicty:04 size:4
Tôi là một lập trình viên xuất sắc, rất giỏi!