Pregunta

I'm reading the source code of flex_string, and doesn't understand very well why the alignment is necessary, just for performance reason?

union
{
    mutable value_type buf_[maxSmallString + 1];
    Align align_;
};

here is link of design document of flex_string:

http://www.drdobbs.com/generic-a-policy-based-basicstring-imple/184403784#4

the author said: But what's that Align business? Well, when dealing with such "seated allocation," you must be careful with alignment issues.

¿Fue útil?

Solución

Quoting from the linked article:

But what's that Align business? Well, when dealing with such "seated allocation," you must be careful with alignment issues. Because there is no portable way of figuring out what alignment requirements Storage has, SmallStringOpt accepts a type that specifies the alignment and stores it in the dummy align_ variable.

I believe this is to do with the Storage template parameter. In order to be as generic as possible, the class is trying to work with any container even if that container has certain alignment requirements for its elements. This could be for performance reasons, or it could to do with compatibility with a certain architecture. The point is, there is no reliable, portable way to ascertain the alignment requirements of whatever "Storage" ends up being.

Hence the parameter Align is intended to be some type whose size is equal to the alignment required by Storage. It is a dummy variable in the union - it is never written to or read. only its size is used.

It can be seen from the code that the small string size is the higher of the configured maximum, and the alignment, making the alignment the minimum configurable small string size.

Hope this helps!

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top