Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 926
There is nothing we can do Avatar asked Dec 17 '22 21:12

There is nothing we can do


2 Answers

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.

like image 167
James McNellis Avatar answered Feb 15 '23 22:02

James McNellis


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 );
}
like image 27
Leniel Maccaferri Avatar answered Feb 16 '23 00:02

Leniel Maccaferri