我今天和我的同事想知道是否可以实现 std::vector 以利用小缓冲区优化。通过查看 C++11 草案,我阅读了 23.3.1p8
The expression a.swap(b), for containers a and b of a standard container type other than array, shall exchange the values of a and b without invoking any move, copy, or swap operations on the individual container elements.
起初这似乎禁止了小缓冲区优化,但在 as-if 规则下,我们仍然可以对非类类型进行小缓冲区优化(因为我们无法观察到正在完成的复制)。接下来的文字似乎更难“愚弄”
Every iterator referring to an element in one container before the swap shall refer to the same element in the other container after the swap.
这是否足以阻止为 std::vector 实现小缓冲区优化?是否有任何其他障碍,或者最终是否有可能在 SBO 中使用 std::vector?
最佳答案
23.2.1/p10/b6:
Unless otherwise specified ...
- no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. ...
对于vector
,它没有“另外指定”。所以这使得 vector
的 SBO 是非法的。
string
不受此规则约束,因为它在 21.4.1/p6 中确实“另有说明”:
References, pointers, and iterators referring to the elements of a basic_string sequence may be invalidated by the following uses of that basic_string object:
- as an argument to any standard library function taking a reference to non-const basic_string as an argument.^234
234) For example, as an argument to non-member functions swap() (21.4.8.8), operator>>() (21.4.8.9), and getline() (21.4.8.9), or as an argument to basic_string::swap()
关于c++ - 可以 std::vector 使用小缓冲区优化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8190950/