开发者

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开发者_C百科 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 );
}


(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.


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++;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜