"Effective C + +": Clause 51: To write new and delete when you need to adhere to the general

Source: Internet
Author: User

clause 50 already explains why to write your own operator new and operator Delete, this article explains what code to follow when writing.

Starting from operator new. Operator new must return the correct value, must call the New-handling function when the memory is insufficient, should have the preparation to deal with 0 memory requirements, avoid accidentally concealing the normal form of the new– this is relatively close to the requirements of the class interface rather than the implementation requirements. The new description of the normal form and clause 52.

operator new if the request for memory succeeds, it returns a pointer to that memory, and failure follows the clause 49 description, throwing the bad_alloc exception. It does not actually know that a memory allocation is attempted at one time, and the new-handling function is called after each failure. This assumes that the new-handling function can do some action to release some memory. An exception is thrown only if the pointer to the New-hangling function is. C + + stipulates that even if the customer requires 0 byte,operator new to return a legitimate pointer. Here is a pseudo-code for non-member operator new (pseudocode):

void*operator New(STD:: size_t size)Throw(STD:: Bad_alloc) {using namespace STD;if(size==0){//Processing 0-byte applicationSize=1; } while(true{Attempt to allocate size bytes;if(Assignment succeeded)returnPoints to the allocated memory;//Allocation failed to find the current new-handling functionNew_handler Globalhandler=set_new_handler (0); Set_new_handler (Globalhandler);if(Globalhandler) (*globalhandler) ();Else Throw STD:: Bad_alloc (); }}

In a multithreaded environment, you also need some kind of locking mechanism to handle the global data structure behind the new-handling function.

It contains a dead loop, and the only way to exit this dead loop is to have the memory allocation successful (assuming new-handling is not null), so the new-handling function does what it does: Make more memory available, install another new-handler, uninstall New-handler , throws a Bad_alloc exception (or its derived class), or admits failure directly to return.

The operator new member function above may be inherited by derived classes. Note Allocate the memory size of a, which is the argument that the function receives. * * clause **50 mentions that custom memory allocators are often optimized for specific class objects, not for the class's derived classes.

classbase{ Public:Static void*operator New(STD:: size_t size)Throw(STD:: Bad_alloc) ...};classDerived: PublicBase{...};//assumed to redefine operator newderived* p=NewDerived;//Call Base::operator new hereIf it isclassThe exclusiveoperator New, this should be changed:void* Base::operator New(STD:: size_t size)Throw(STD:: Bad_alloc) {if(size!=sizeof(Base))return::operator New(size);//using the standard operator new......}

If you plan to control arrays memory allocations for class-specific editions, you need to implement operator new[]. The only thing to do when writing operator new[] is to allocate a piece of raw memory, because you can't do anything about an element object that has not existed in the array so far. We don't even know how many element objects this array contains. You may not know how large each object is because the base class operator new[] is likely to be called through inheritance, allocating memory to an array of derived class objects.

So no more base::operator new[] assume that the size of each element object is sizeof (base), so that you cannot assume that the number of array elements is (bytes number of/sizeof (base)). In addition, the size_t parameter passed to operator new[] may have a value that is larger than the memory of the generation object, since clause 16 mentioned that dynamically allocated arrays may contain additional space to hold the number of elements.

Operator delete is a lot easier, but keep in mind that C + + guarantees that the removal of pointers is always safe. Here is the pseudo-code for non-member operator Delete (pseudocode):

voidoperatordelete(voidthrow(){    if(rawMemory==0return;    归还rawMemory所指内存;}

The member version of this function is also very simple, just add a check to delete the number.

void Base::operatordelete(voidstdthrow(){    if(rawMemory==0return;    if(size!=sizeof(Base)){        ::operatordelete(rawMemory);        return ;    }    归还rawMemory所指内存;    return ;}

If the object to be deleted derives from a base class and the latter does not have a virtual destructor, the size_t value passed to operator delete by C + + may be incorrect.

Summarize

    • Operator new should have a dead loop in it and try to allocate memory in it, and if it can't meet the memory requirements, call New-handler. It should also have the ability to handle 0bytes applications. The class-specific version should also handle "larger (error) applications than the correct size."
    • operator delete should not do anything when the pointer is received. The class-specific version should also handle "larger (error) applications than the correct size."

"Effective C + +": Clause 51: To write new and delete when you need to adhere to the general

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.