这个简单的例子被视为RAII

use*_*128 1 c++ raii

从绩效角度来看,还有更好的方法吗?

例如,创建一个名为arraydata的类/结构,它分配一些对齐的内存供使用(尽管由.dataPtr提供的指针):

class arraydata//to allocate some memory, 
               //and return a pointer to that block of memory
{
    void *dataPtrV;

  public:

    double *dataPtr;

    arraydata(int a, int b)
    {
        dataPtrV=_aligned_malloc(a*b*sizeof(double),32);
        dataPtr=(double *)dataPtrV;
    }

    ~arraydata()
    {
        _aligned_free(dataPtrV);
        dataPtrV=NULL;
        dataPtr=NULL;
    }   
};
Run Code Online (Sandbox Code Playgroud)

然后叫它:

     arraydata X(30,20);
Run Code Online (Sandbox Code Playgroud)

Pub*_*bby 6

是的,这将被视为RAII - 资源在构造函数中获取并在析构函数中释放.

我不知道为什么你要存储一个void*和一个double*- 只有一个double*应该就足够了.

此外,在复制课程时要非常小心,因为这很容易导致泄漏并释放已经释放的数据.

无论如何,这也可以使用std::unique_ptr哪个更惯用,没有你的课程垮台:

struct aligned_free {
  void operator()(void* p) {
     _aligned_free(p);
  }
};

template<typename T>
T* aligned_malloc(std::size_t size, std::size_t alignment) {
  return static_cast<T*>(_aligned_malloc(size * sizeof(T), alignment));
}

std::unique_ptr<double, aligned_free> make_array_data(int a, int b) {
    return std::unique_ptr<double, aligned_free>(aligned_malloc<double>(a*b, 32));
}

auto arraydata = make_array_data(30, 20);
Run Code Online (Sandbox Code Playgroud)

这是你的班级没有void*:

class arraydata//to allocate some memory, 
               //and return a pointer to that block of memory
{

  public:

    double *dataPtr;

    arraydata(int a, int b)
    {
        dataPtr=static_cast<double*>(_aligned_malloc(a*b*sizeof(double),32));
    }

    ~arraydata()
    {
        _aligned_free(dataPtr);
    }   
};
Run Code Online (Sandbox Code Playgroud)