![](/img/trans.png)
[英]How does the std::basic_string constructor know beforehand how much space to reserve?
[英]std::basic_string::reserve() specifics
我正在阅读std::basic_string::reserve(size_type res_arg=0)
。 它说:
void reserve(size_type res_arg=0);
成员函数
reserve()
是一个指令,用于通知basic_string
对象计划中的大小更改,以便它可以相应地管理存储分配。效果:在
reserve()
,capacity()
等于或大于reserve的参数。 [ 注意:调用res_arg参数小于Capacityreserve()
的reservecapacity()
实际上是一个非绑定收缩请求。 使用res_arg <= size()
调用res_arg <= size()
是一个非绑定的“缩小以适合”请求。 —尾注]抛出:如果
res_arg > max_size()
则为res_arg > max_size()
标准似乎是使呼叫区分reserve()
其中res_arg < capacity()
和调用reserve()
其中res_arg <= size()
res_arg <= size()
很容易理解, shrink_to_fit()
,并且实现是自由执行的,因为它是非绑定的。
但是res_arg < capacity()
呢? 该标准说“ 非约束性收缩请求 ”而不是“ 非约束性收缩适应请求 ”。 缩小至匹配请求与缩小请求之间有什么区别? 这只是不幸的矛盾之处吗?
std::string::shrink_to_fit()
将收缩capacity()
的size()
那是不同的,然后将Capacity capacity()
缩小到一个小于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
缩小以适合:减小容量以适合尺寸。
Google首先提到的是向量 。
缩小得恰到好处,缩小(容量下降)。 如果您保留的空间较小,那么实质上是当前的大小,该大小将准备减少容器以适合较短的字符串,因此称为“适合”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.