Effective C + + clause 51 you need to stick to the general rules when writing new and delete

Source: Internet
Author: User

1. Implementation of custom operator new AND operator delete requires a certain amount of requirements to be met.

In the case of operator NEW: consistency operator new must return the correct value, the New-handling function must be called when there is insufficient memory, there is a need to deal with 0 of memory requirements, to avoid inadvertent concealment of the normal form of new, if you have the ability to supply the memory of the customer application, Returns a pointer to the memory, which in turn follows the rules of Clause 49 and throws a Bad_alloc exception; an infinite loop should be included, knowing that the memory is allocated successfully or new-handling to complete its function ...

The above requirements "must have to deal with 0 memory requirements of the preparation" means that even if the customer requires 0 Bytes,operator also have to return a legitimate pointer.

2. Here is a non-member operator new pseudo-code:

void*operator New(std::size_t size)Throw(std::bad_alloc) {using namespacestd; if(size==0) Size=1;  while(true{Attempt to allocate size bytes; if(Assignment succeeded)return(a pointer that points to the allocated memory); New_handler Globalhandler=set_new_handler (0);        Set_new_handler (Globalhandler); if(Globalhandler) (*Globalhandler)        (); Else            ThrowStd::bad_alloc (); }}
View Code

It is important to note that the operator new member function is inherited by derived classes, which leads to some interesting complexities. A common reason to write a custom memory manager is to provide optimization for object assignment behavior for a particular class. Rather than for any derived class of the class, that is, the operator of the design of a particular type, its behavior may be typically only designed for sizes that are just about the size of the object. However, once inherited, it is possible that the base class's operator New is called to assign the derived class object:

class base{public:    staticvoidoperatornewThrow  (std::bad_alloc);    ...}; class Derived: public base{...   };D erived*p =new// call here Base::o PERAOTR new!
View Code

Base class exclusive operator new is often not used to allocate memory for derived class objects, and the workaround is to change the standard operator new by invoking the "Memory request Error" behavior:

void * Base::operatornewthrow(std::bad_alloc) {    if(size ! =sizeof(Base)        )return ::operatornew(size);    ...}
View Code

If you want to implement a custom version of operator new[], then operator new[] The only thing to do is allocate a piece of memory, and cannot do anything to an element that does not already exist in the array, setting cannot calculate how large each element object is, in fact, the C + + standard operator The default operation for new[] is done via operator new (http://www.cplusplus.com/reference/new/operator%20new[]/?kw=operator%20new[]).

Operator delete is relatively simple, the only thing to note is that C + + guarantees "Remove null pointer always safe", the following is the pseudo-code of Non-member operator Delete:

void operator Delete (voidthrow() {    if(rawmemory==0)        return ;    Return the memory referred to by rawmemory;}
View Code

Operator Delete Member version is also relatively simple, only need to add an action to check the number of deletions. In case the class-specific operator new transfers the wrong-sized distribution:: operator new executes, and the deleted behavior of the wrong size must also be forwarded: : operator Delete execution:

classbase{ Public:    Static void*operator New(std::size_t size)Throw(Std::bad_alloc); Static void operator Delete(void* rawmemory,str::size_t size)Throw(); ...};voidBase::operator Delete(void* rawmemory,std::size_t size)Throw(){    if(rawmemory==0)        return; if(size!=sizeof(Base)) {        ::operator Delete(rawmemory); return;    Now, return the memory that rawmemory refers to; return;}
View Code

It is important to note that if the object to be deleted derives from a base class and the latter lacks a virtual destructor, the size_t value passed to operator delete by C + + may be incorrect. That is, operator The normal operation of delete depends on the function of the destructor (if there is a destructor).

Effective C + + clause 51 you need to stick to the general rules when writing new and delete

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.