To hold arbitrarily large objects, boost::any
/ std::any
surely needs to allocate heap space for objects. However, for small types whose size is less or equal to a pointer (int,char,bool,...
), any
could instead store the value in-place in the pointer slot or in some other in-place memory and not allocate heap space. But does the implementation do this?
I have a scenario where I often store small types in an any
and only sometimes larger types like string
s. The code is quite hot and therefore I am asking the question. If the optimization is not performed, I might be better off with an own implementation that stores small types in-place.
There is no guarantee but the C++17 draft states in [any.class] that
Implementations should avoid the use of dynamically allocated memory for a small contained object. [ Example: where the object constructed is holding only an int. — end example ] Such small-object optimization shall only be applied to types
T
for whichis_nothrow_move_constructible_v<T>
istrue
.
Unfortunately it does not give a recommendation for what should be considered small except to say a int
should be able to be stored in place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With