What is the purpose of the second parameter to std::allocator<T>::deallocate?

In here is declaration of deallocate mem. of allocator class. My question is what for is second argument in this declaration? If this function calls operator delete(_Ptr) this argument is unused so what's for is it there?
Thanks.

Excerpt from MSDN:

Frees a specified number of objects from storage beginning at a specified position.

void deallocate(
   pointer _Ptr, 
   size_type _Count
);  

Parameters

_Ptr A pointer to the first object to be deallocated from storage.

_Count The number of objects to be deallocated from storage.

Upvotes: 4

Views: 824

Answers (4)

James McNellis
James McNellis

Reputation: 355197

When you call deallocate, you must give it a pointer that you previously obtained from calling allocate and the size that you passed to allocate when you initially allocated the memory.

For example,

#include <memory>

std::allocator<int> a;
int* p = a.allocate(42);
a.deallocate(p, 42);     // the size must match the size passed to allocate

This is useful for many different types of allocators. For example, you may have an allocator that uses different pools for blocks of different sizes; such an allocator would need to know what the size of the block being deallocated is so that it knows to which pool it needs to return the memory.

Upvotes: 7

Leniel Maccaferri
Leniel Maccaferri

Reputation: 102428

It's not unused.

From MSDN:

Frees a specified number of objects from storage beginning at a specified position (_Ptr in this case).

Parameters

_Ptr A pointer to the first object to be deallocated from storage. (start position)

_Count The number of objects to be deallocated from storage.

Sample code:

// allocator_allocate.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>
#include <vector>

using namespace std;

int main( ) 
{
   allocator<int> v1Alloc;

   allocator<int>::pointer v1aPtr;

   v1aPtr = v1Alloc.allocate ( 10 );

   int i;
   for ( i = 0 ; i < 10 ; i++ )
   {
      v1aPtr[ i ] = i;
   }

   for ( i = 0 ; i < 10 ; i++ )
   {
      cout << v1aPtr[ i ] << " ";
   }
   cout << endl;

   v1Alloc.deallocate( v1aPtr, 10 );
}

Upvotes: 5

ngroot
ngroot

Reputation: 1176

It appears to me that it's expecting _Ptr to be a pointer into an array of objects, and that it's basically doing:

for (size_type i = 0; i<_Count; i++) {
    delete _Ptr;
    _Ptr++;
}

Upvotes: 0

Max
Max

Reputation: 3180

(reference the example in the documentation for the allocator : http://msdn.microsoft.com/en-us/library/723te7k3.aspx)

I assume that the allocator does not do a new[] and does not keep the number of allocated elements so it cannot do a delete[] ?

so the user need to tell how many to allocate and how many to deallocate.

M.

Upvotes: 0

Related Questions