c++ - delete(void *, size_t) or delete(void *)

In my previous dicuss, we have seen the example of overloaded delete and new operator. and as a matter of fact, we have seen the following signature of the delete operator. 

 

 

void operator delete(void *);
void operator delete(void *, size_t size);

 

 

As you will soon find out that they both match the same new operator

 

void operator new (size_t);

 

but which one should we  choose to use?

 

and even, you can define both the operator delete(void *) and the operator delete (void *, size_t) in the same class, and according to my test , in the placement operator overloading example, the "operator delete(void *)" has precedance over the "operator delete (void *, size_t)"....

 

so here is my rule of thme, we uses operator delete (void *, size_t size) when 

 

  • the size_t is not barely the size of the object (this could happen if the new operator has say, preallocate some space which is larger than what is required by the object itself.)
  • the size_t is necessary to determine flows or it is necessary in the clean up that the delete operator is supposed to do.
  • Booking and logging requirement.
  • This can be thought as an extension to the point 2, where you can normally see allocated memory is larger than the object itself, is when you allocate a array (new [] operator actually does this)....

 

And when to use the operator delete (void *)?

 

  • when the size of the pointer in the first parameter is exact the size of the object
  • The size_t size is irrelevant in the deallocation flow. 

 

 

 

 

 

你可能感兴趣的:(C++)