cuốn sách gpt4 ai đã làm

c++ - chi tiết std::basic_string::reserve()

In lại Tác giả: Walker 123 更新时间:2023-11-28 05:10:18 32 4
mua khóa gpt4 Nike

我正在阅读 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() 的情况呢? ?该标准说的是“非约束性收缩请求”而不是“非约束性收缩至适合请求”。收缩至合身请求和收缩请求之间有什么区别?这只是一个不幸的不一致吗?

câu trả lời hay nhất

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

关于c++ - std::basic_string::reserve() 细节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43667171/

32 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress