尝试使用std::aligned_storage与SSE和new

Trying to use std::aligned_storage with SSE and new

本文关键字:storage SSE new aligned std      更新时间:2023-10-16

我想尝试在c++中使用SSE指令获得一些浮点数的平方根。但是当我试图存储结果时,我得到了一个异常。我可以像那样使用std::aligned_storage吗?

#include <iostream>
#include <type_traits>
#include <xmmintrin.h>
using namespace std;
using float_storage = aligned_storage<4 * sizeof(float), 16>;
int main()
{
    int N;
    cin >> N;
    float_storage * values = new float_storage[ N / 4 ]; // 4 floats in pack
    for(int i = 0; i < N / 4; i++)
    {
        void *vptr = static_cast<void*>(&values[i]);
        float *fptr = static_cast<float*>(vptr);
        for(int i = 0; i < 4; i++)
            cin >> fptr[i];
    }
    for(int i = 0; i < N / 4; i++)
    {
        void *vptr = static_cast<void*>(&values[i]);
        float *fptr = static_cast<float*>(vptr);
        __m128 x = _mm_loadu_ps(fptr);
        x = _mm_sqrt_ps(x);
        _mm_store_ps(fptr, x); // im getting an crash here
    }
    for(int i = 0; i < N / 4; i++)
    {
        void *vptr = static_cast<void*>(&values[i]);
        float *fptr = static_cast<float*>(vptr);
        for(int i = 0; i < 4; i++)
            cout << fptr[i] << endl;
    }
    delete[] values;
}

aligned_storage<size, align>::typealigned_storage本身只是一个元编程结构体。

另外,如果我没记错的话,new只被评为std::max_align_t,即使您new设置了具有更高对齐要求的类型。