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.
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.
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 );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With