If operator new receives parameters other than size_t, then this operator new is actually a placement new, so consider the following scenario:
A placement new that can be used to record information:
1 classwidget{2 Public:3 ...4 Static void*operator New(std::size_t size, std::ostream & logstream =std::cout)5 Throw(std::bad_alloc);6 Static void*operator Delete(void* Pmem, std::size_t size)Throw();7 ...8};
So when we create a new widget:
1 New (Std::cerr) Widgets;
At this point, if the new is successful but fails to construct the widget, then the system cannot find the corresponding delete to release the allocated raw memory, which will cause a memory leak. So when providing placement new, be sure to provide the corresponding placement delete so that no memory leaks occur. Placement Delete is as follows:
1 Static void operator Delete (void * pmem, std::ostream& logstream);
The simple form of completing all the points is to create a base class that contains all the normal forms of new and delete. The simple form of completing all the points is to create a base class, Contains all the normal forms of new and delete. The simple form of completing all the points is to create a base class that contains all the normal forms of new and delete.
1 classstandardnewdeleteforms{2 Public:3 //Normal New/delete4 Static void*operator New(std::size_t size)Throw(Std::bad_alloc)5 {6 return::operator New(size);//The Global new is used here.7 }8 Static void operator Delete(void* Pmem)Throw()9 {Ten return::operator Delete(PMEM); One } A //Placement New/delete - Static void*operator New(std::size_t size,void* ptr)Throw() - { the return::operator New(size, ptr); - } - Static void operator Delete(void* Pmem,void* ptr)Throw() - { + return::operator Delete(Pmem, PTR); - } + //nothrow New/delete A Static void*operator New(std::size_t size,ConstStd::nothrow_t & NT)Throw() at{return::operator New(size, NT);} - Static void operator Delete(void* Pmem,ConstStd::nothrow_t & NT)Throw() -{return::operator Delete(Pmem, NT)} -};
You can then use both inheritance and the using declaration to get the new and delete you want:
1 classWidgets: Publicstandardnewdeleteforms{2 Public:3 usingStandardnewdeleteforms::operator New;4 usingStandardnewdeleteforms::operator Delete;//introduce them to the scope so that the global new and delete are obscured. 5 Static void*operator New(std::size_t size,6Std::ostream & LogStream)Throw(std::bad_alloc);7 Static void*operator Delete(void*Pmem,8Std::ostream & LogStream)Throw();9};
Clause 52: Thanks placement new also should write a placement delete