In Visual Studio 2005, 2010 and possibly many other versions, whenever you try to store aligned data structures into a std::vector you'll get the following error:
error C2719: '_Val': formal parameter with __declspec(align('16')) won't be aligned
Here's a code snippet that triggers this error:
#include <vector>
struct __declspec(align(16)) S
{
int x;
};
int main()
{
std::vector<S> v;
return 0;
}
This is a well known and well documented issue in Visual Studio's implementation of the STL library.
The common workaround seems to revolve around dropping std::vector in favor of some kind of custom container that doesn't have this problem.
I found another workaround that I didn't see mentioned elsewhere: templatize the data structure that requires alignment. Here is an example that compiles and appears to work correctly:
#include <vector>
template <typename>
struct __declspec(align(16)) S
{
int x;
};
int main()
{
std::vector<S<void>> v;
return 0;
}
Obviously the template parameter isn't used and can be set to anything.
Update Feb. 22, 2012: It's not so simple. The dreaded C2719 error may appear again if the type (S<void>) was instantiated earlier in the translation unit, but this will also depend on the bitness (32-bit vs. 64-bit), the alignment value and probably the size of S<void>. To summarize:
| Type instantiated earlier? |
Bitness |
Alignment |
Result |
| No |
Any |
Any |
OK |
| Yes |
32-bit |
16 bytes |
C2719 |
| Yes |
32-bit |
32 bytes |
C2719 |
| Yes |
32-bit |
64 bytes |
C2719 |
| Yes |
64-bit |
16 bytes |
OK |
| Yes |
64-bit |
32 bytes |
OK |
| Yes |
64-bit |
64 bytes |
C2719 |
Yuck.
Update Feb. 23, 2012: I outlined a more robust solution in this post on StackOverflow.