The solution is to let class Foo have an aligned "operator new", as we showed in the previous section.
That's not required. Since Eigen takes care of declaring 128-bit alignment, all members that need it are automatically 128-bit aligned relatively to the class. So code like this works fine:
Dynamic-size matrices and vectors, such as Eigen::VectorXd, allocate dynamically their own array of coefficients, so they take care of requiring absolute alignment automatically. So they don't cause this issue. The issue discussed here is only with fixed-size vectorizable matrices and vectors.
No, it's not our bug. It's more like an inherent problem of the C++98 language specification, and seems to be taken care of in the upcoming language revision: see this document.
For this situation, we offer the macro EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(NeedsToAlign). It will generate aligned operators like EIGEN_MAKE_ALIGNED_OPERATOR_NEW if NeedsToAlign is true. It will generate operators with the default alignment if NeedsToAlign is false.
In case putting the EIGEN_MAKE_ALIGNED_OPERATOR_NEW macro everywhere is too intrusive, there exists at least two other solutions.
The first is to disable alignment requirement for the fixed size members:
This has for effect to disable vectorization when using
The second consist in storing the fixed-size objects into a private struct which will be dynamically allocated at the construction time of the main object:
The clear advantage here is that the class Foo remains unchanged regarding alignment issues. The drawback is that a heap allocation will be required whatsoever.
Passing objects by value is almost always a very bad idea in C++, as this means useless copies, and one should pass them by reference instead.
With Eigen, this is even more important: passing fixed-size vectorizable Eigen objects by value is not only inefficient, it can be illegal or make your program crash! And the reason is that these Eigen objects have alignment modifiers that aren't respected when they are passed by value.
So for example, a function like this, where v is passed by value:
needs to be rewritten as follows, passing v by reference:
Likewise if you have a class having a Eigen object as member:
This function also needs to be rewritten like this:
Note that on the other hand, there is no problem with functions that return objects by value.