r/cpp • u/User_Deprecated • Aug 26 '26
C++26: std::inplace_vector
https://www.sandordargo.com/blog/2026/08/26/cpp26-inplace-vector
181
Upvotes
r/cpp • u/User_Deprecated • Aug 26 '26
View all comments
Show parent comment
1
u/KuntaStillSingle Aug 28 '26
For a pointer in many platforms the upper bits are not used, so you have possible signalling representations that could be used to encode size. For example if N is 32, and the number of available tag bits is 6, you can get size by the following method:
Check the last element, if all 6 upper bits are 0 or 1 it is potentially canonical and this means size == capacity (the last element presumably contains an actual pointer rather than a pointer tagged with capacity, therefore it is full.). Otherwise, the first bit is opposite of the second bit, and the remaining 5 bits encode size as an unsigned int. For example if size == 0, then the last pointer would look like (1000 0000 0000 ...), where if size == capacity and the last pointer is nullptr it would be (0000 0000 0000 ...), and if size == 1 then it looks like (1000 0100 0000 ...), and if size = 31 then it looks like (0111 1100 0000 ...).
This would make the container incapable of properly storing user supplied tagged pointers, but this is allowed, handling of invalid pointers is implementation defined with exception of where it is undefined: https://en.cppreference.com/cpp/language/pointer#Invalid_pointers
It would be less dirty for an implementation to do it when T is a std library object that stores a pointer the user doesn't expect to be able to tag, for example a libstdc++ string doesn't use the pointer space for SSO, so inplace_vector<std::string, N> could be specialized to use the taggable bits in the last element if the inplace vector is not full (either the last string element has not been constructed, or it has been destroyed during a pop_back or the like, so it does not matter that you are using the pointer for book keeping, or if it is full and contains an actual string object, you are only reading the pointer for bookkeeping, not writing it.)