Search code examples
c++castingallocation

c++ deallocator lost after cast?


I have a custom allocator for a vector, but I would rather not have it in the code everywhere. So I thought to cast it to a normal vector

vector<Complex> * createVector(size_t nfft)
{
    vector<Complex,fftalloc<Complex > > * data = new vector<Complex,fftalloc<Complex > >(nfft);
    return reinterpret_cast<vector<Complex> *>(data);
}

my allocator/deallocator functions print out if they are called:

   pointer allocate (size_type num, const void* = 0) {
       // print message and allocate memory with global new
       ALLOCDEBUG << "allocate " << num << " element(s)"
       ...
   }

   void deallocate (pointer p, size_type num) {
       // print message and deallocate memory with global delete
       ALLOCDEBUG << "deallocate " << num << " element(s)"
       ...
   }

But a test with

    {
        vector<complex<double> > * v;
        v = fft.createVector(16);
        v->push_back(1);
        delete v;
    }

prints out only the allocate function.

Is it possible to cast without loosing the deallocator?


Solution

  • The problem here is that the allocator is a property of the template, not stored as part of the vector or something. So when you cast from one type of vector to another, you are changing allocator element of the template type.

    The simplest way [in terms of typing] to solve this is to declare a type, e.g. typedef vector<double, fft_alloc<double> > fftdouble; - using template declaration can help to make many such types.

    You can't swap and change which allocator you use, and there is no trivial solution [in current standards].