Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

c++ - May std::vector make use of small buffer optimization?

I was wondering with my colleague today whether std::vector can be implemented to make use of small buffer optimization. By looking into the C++11 draft, I read at 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.

That at first seems to outlaw small buffer optimization, but under the as-if rule, we would be allowed to still do small buffer optimization for non-class types (since we cannot observe the copy being done). The next text appears to be harder to "fool"

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.

Is this sufficient to prevent implementing the small buffer optimization for std::vector? Are there any other road-blocks or is it eventually possible to have a std::vector with SBO?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. ...

Nowhere does it "specify otherwise" for vector. So this outlaws the SBO for vector.

string is not bound by this rule because it does "specify otherwise" in 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()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...