0

I know that std::string has small-string optimization, and both std::any and std::function have small-object optimization.

Are these optimizations just implementation details, or are they specified in standard? If they're specified in standard, then which classes have small-object optimization?

I found some related words in spec:

22.7.4:Implementations should avoid the use of dynamically allocated memory for a small contained value. However, any such small-object optimization shall only be applied to types T for which is_­nothrow_­move_­constructible_­v is true.

But I can't find a specification for small-object optimization.

Any additional supplements and recommendations are appreciated.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Mes
  • 177
  • 7
  • 7
    "*Are these optimizations just implementation details*" - yes "*are they specified in standard*" - no – Remy Lebeau May 24 '22 at 20:41
  • 3
    When it gets down to the nuts-and-bolts, the C++ Standard is pretty hands-off in order to offer plenty of leeway for optimization and strange implementations targeted at strange problems. – user4581301 May 24 '22 at 20:46
  • @RemyLebeau Does that mean `std::string` may not have small string optimization for some compiler? – Mes May 24 '22 at 20:48
  • 2
    @Mes yes, SSO is optional. It is an implementation detail, and while most modern implementations do utilize it, not every one does. – Remy Lebeau May 24 '22 at 20:55
  • @RemyLebeau okay, that sovle my question, thank you very much. But I wonder if most container utilize small object optimization, just like `std::any` and `std::function` do, ofc in most compiler. – Mes May 24 '22 at 21:01
  • 2
    No, other containers do not. Most famously std::vector is not allowed because of the iterator invalidation rules, like iterators staying valid after a swap with another vector! https://en.cppreference.com/w/cpp/container/vector/swap – BoP May 24 '22 at 21:13
  • @BoP okay, got it, that surprise me a lot, thank you very much :) – Mes May 24 '22 at 21:16
  • In standardese, "should" means that it's highly recommended. It does **not** impose a requirement (a requirement would use "shall"). So the quoted text does not require small-string optimization. – Pete Becker May 24 '22 at 22:04
  • @Bop Just to be clear (in case anyone gets misled over this) cppreference is playing a bit fast and loose with their terminology here. The iterators remain valid, but now refer to the _'other'_ vector, see: https://stackoverflow.com/a/4125186/5743288. Apologies if this sounds obvious - it could hardly work any other way. – Paul Sanders May 24 '22 at 23:04

0 Answers0