John Zeng John Zeng - 5 months ago 30
C++ Question

When and why will this function return something else

I am reading the CPP's STL code to figure out something. And I reach a function in vector header file, the function is :

static size_type __align_it(size_type __new_size) _NOEXCEPT

{return __new_size + (__bits_per_word-1) & ~((size_type)__bits_per_word-1);};

size_type is size_t, and __bits_per_word is :

static const unsigned __bits_per_word = static_cast<unsigned>(sizeof(__storage_type) * CHAR_BIT);

My compiler is clang and the version is like clang-800.x.xx.

My question is , when and why will __align_it return something else than __new_size.


It will return something different than __new_size when __new_size is not dividable by __bits_per_word. In other words this function is used to round the __new_size to nearest multiple of __bits_per_word.

This is very common function used to properly align structure members if not automatically determined by compiler. For example when we have char array but we still want to align it to the same address as unsigned field because of access optimization.