Search code examples
c++raii

Is this simple example considered as RAII


And peformance-wise, are there some better ways to do that?

for example, create a class/struct called arraydata, it allocates some aligned memory for use (though a pointer provided by .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;
    }   
};

Then call it by:

     arraydata X(30,20);

Solution

  • Yes, that would be considered RAII - the resource is acquired in the constructor and released in the destructor.

    I'm not sure why you're storing both a void* and a double* though - only a double* should suffice.

    Also, be extremely careful when copying your class as that will easily lead to leaks and freeing already freed data.

    Anyway, this can also be done using std::unique_ptr which is more idiomatic and without the downfalls of your class:

    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);
    

    Here's your class without 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);
        }   
    };