以下在 MSVC 上编译时没有警告。
#include <iostream>
#include <emmintrin.h>
int main()
{
__declspec(align(16)) int x = 42;
std::cout << &x << "\n"; // Print out the address that holds x
__m128i v = _mm_load_si128((__m128i const*)(x));
}
本质上,代码对齐一个 32 位整数,并尝试将其加载到 __m128i 类型中。 _mm_load_si128
要求输入地址为 16 字节对齐。 _mm_loadu_si128
不需要它,但两者都会导致上述代码在运行时发出访问冲突。为什么,我该如何解决?
最佳答案
你忘了取x
的地址:
__m128i v = _mm_load_si128((__m128i const*)(&x));
// ^
// |
// Here ----------------+
此外,您没有为数据提供足够的空间,因此 _mm_load_si128
最终会读取已分配内存块的末尾。
关于c++ - 为什么即使是 16 字节对齐的地址也会导致 _mm_load_si128 导致访问冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881224/