Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does boost::any / std::any store small objects in-place?

Tags:

c++

c++17

boost

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

like image 526
gexicide Avatar asked Jan 26 '17 16:01

gexicide


1 Answers

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 which is_­nothrow_­move_­constructible_­v<T> is true.

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.

like image 114
NathanOliver Avatar answered Sep 23 '22 13:09

NathanOliver