c++ - 可以 std::vector 使用小缓冲区优化吗?

标签 c++ c++11 stdvector

我今天和我的同事想知道是否可以实现 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/

相关文章:

c++ - Type t = Type() 是否调用复制构造函数?

c++ - C/C++取值为0的整型变量求反

c++ - 将 GNU C++ 程序移植到 Visual C++

c++ - lambda 队列是 C++11 中工作队列的良好设计模式吗?

c++ - 为什么 push_back() 会导致 malloc() 处理的数据崩溃?

c++ - Python 和 pygame 是学习 SDL 的好方法吗?

c++函数的返回类型是其输入的函数

c++ - 如何使用 std::rand 生成非重复的随机数序列

c++ - 什么 vb6 类型与 std::vector 兼容 ABI?

c++ - 使用 C++ 将整数 vector 写入二进制文件的更快方法?