Reputation: 613
SSO (small/short string optimization) can be used for std::string
. But is it allowed to be used in other standard library containers (e.g. std::vector
)? Does the answer depend on whether or not the template parameters of the containers are builtin types or user-defined types?
Upvotes: 3
Views: 890
Reputation: 303537
The broader term is SBO - small buffer optimization. SSO is string specific.
Anyway, most of the other containers in the standard library cannot make use of SBO due to iterator invalidation rules. The standard guarantees that an iterator into a container remains valid through a move. That is:
std::vector<T> v = ...;
auto iter = v.begin(); // assume v is non-empty
std::vector<T> new_v = std::move(v);
foo(*iter); // *must* be okay
This guarantee is impossible to meet with SBO - since iter
could point into the automatic storage of vs
, which cannot magically transfer into new_v
. std::string
does not have this kind of guarantee, so it's okay.
On the other hand, something like std::function<>
can (and typically does) implement SBO, since there is no such move guarantee. That's not really a container in the containers sense.
Upvotes: 10