C + + new, delete (new[], delete[]) operator overloading the issues that need attention _c language

Source: Internet
Author: User
Tags exception handling

Overloads of the new, delete (new[), delete[] operators require attention:

1. The overloaded new, delete (or new[], delete[) operator must be a static member function of the class (why it must be a static member function, which is well understood because the new operator is called, the object is not built), or is a global function, The prototype of the function is as follows:

Copy Code code as follows:

void* operator new (size_t size) throw (Std::bad_alloc);
Size here is the total size of the allocated memory
void* operator new[] (size_t size) throw (Std::bad_alloc);

void operator Delete (void* p) throw ();
void operator delete[] (void* p) throw ();

void operator Delete (void* p, size_t size) throw ();
Parameter size difference from new[], where size is not the total size of the freed memory
void operator delete[] (void* p, size_t size) throw ();

In addition, we can use different parameters to overload the new, delete (or new[], delete[] operators, for example:

Copy Code code as follows:

The first argument is still size_t
void* operator new (size_t size, const char* file, int line);
Use of this operator
string* str = new (__file__, __line__) string;

Overloading the global new, delete (or new[), delete[] operators changes all default allocation behavior, including the assignment behavior of a class, so you must be careful to use the link error if all two libraries are new, and so on global overload (duplicated Symbol link error). The new, delete (or new[), delete[] operators defined in the class affect only this class and derived classes.

Many people are completely unaware that operator new, operator delete, operator new[, operator delete[] member functions are inherited (although they are static functions). Sometimes, we just want to set the custom operator new member function for the specified class, and not want to affect the subclass's work. The effective C + + third Edition provides the following scenarios:

Copy Code code as follows:

void * Base::operator new (std::size_t size) throw (Std::bad_alloc)
{
If the size is not the base class size
if (size!= sizeof (Base))
Calling the standard new operator
Return:: operator new (size);

Custom size allocation processing for base class size
}

One precondition for this is that the child class must be larger than the parent class.

For operator new[], it is difficult to check whether a parent or subclass invokes an operator in the above way. With the parameters of the operator new[] operator, we cannot know the number of elements allocated and the size of each element allocated. The parameters of operator new[] size_t indicate that the size of the memory allocation may be greater than the sum of the memory size of the elements that need to be allocated, because dynamic memory allocations may allocate additional space to hold the number of array elements.

2. Compatible with the default new, delete error handling method

This is not a very simple matter (refer to "effective C + + third Edition" Item 51). operator new is usually written like this:

Copy Code code as follows:

Multithreaded access is not considered here
void* operator new (std::size_t size) throw (Std::bad_alloc)
{
using namespace Std;

Size = 0 o'clock new also must return a valid pointer
if (size = = 0)
size = 1;

while (true) {

Attempt to allocate memory

If (memory allocation succeeded)
Return (the address of the memory allocated successfully);

Find the current new-handling function when memory allocation fails
Because there is no direct access to the new-handling function, so this is the only way
New_handler Globalhandler = set_new_handler (0);
Set_new_handler (Globalhandler);

If a new-handling function is present, call the
if (Globalhandler) (*globalhandler) ();
Throw an exception if no new-handling function exists
else throw Std::bad_alloc ();
}
}

These are some of the things we need to be aware of: operator new can accept a memory allocation of size 0 and return a valid pointer, and if there is a new-handling function, it is called when the memory allocation fails and the memory allocation is attempted again; A Bad_alloc exception is thrown when the new-handling function fails.

It is important to note that once the New-handling function memory allocation is set up indefinitely, in order to avoid infinite loops, the new-handling function must do one of several things (refer to effective C + + Third Edition "Item 49": Allow more memory to be available, set another functioning New-handler, delete the current new handler, throw an exception (Bad_alloc or inherit from Bad_alloc), and invoke the abort directly () or a function such as exit ().

The exception handling for the operator delete is simpler, with only the safe delete null pointer to be guaranteed:

Copy Code code as follows:

void operator delete (void *rawmemory) throw ()
{
Operator can accept null pointer
if (rawmemory = = 0) return;

Free memory
}

Polymorphic issues (refer to ISO/IEC 14882 for details)

The inheritance of the new, delete (new[), delete[] operator is discussed here for an additional discussion of polymorphic issues, and obviously we just need to discuss the delete, delete[] operators:

Copy Code code as follows:

struct B {
Virtual ~b ();
void operator Delete (void*, size_t);
};

struct D:B {
void operator Delete (void*);
};

void F ()
{
b* bp = new D;
Delete bp; 1:uses d::operator Delete (void*)
}

With the example above, we can see that the operator delete operator of D is called correctly at delete. But again, the delete[] operator is not working properly (because the check for the delete[] operator is static):

Copy Code code as follows:

struct B {
Virtual ~b ();
void operator delete[] (void*, size_t);
};

struct D:B {
void operator delete[] (void*, size_t);
};

void f (int i)
{
d* DP = new D[i];
delete [] DP; Uses D::operator delete[] (void*, size_t)
b* BP = new D[i];
Delete[] BP; Undefined behavior
}

Related Article

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.