The difference between operate new () and new operate

Source: Internet
Author: User
operator new and new operator

Reprint a article about new

operator new and new operator collection

C + + operator new and new operator, looks like the two sisters, but there is a difference.

operator NEW

(1) Allocate only the required space and do not invoke the constructor of the related object. When the required allocated space is not met, the

-> If there is a new_handler, call New_handler, otherwise

-> If there is no requirement not to throw an exception (expressed as a nothrow parameter), then the bad_alloc exception is executed, otherwise

-> return 0

(2) can be overloaded

(3) When overloaded, the return type must be declared as void*

(4) When overloaded, the first parameter type must be the size (in bytes) of the expression requirement allocation space, and the type is size_t

(5) When overloaded, can take other parameters

New operator

(1) Call operator new to allocate enough space and call the constructor of the related object

(2) can not be overloaded

Accordingly, the operator delete has similar characteristics to the delete operator.

As an example

Class X
{
Public
............
Static void* operator new (size_t size)
{
Return:: operator new (size);
}
static void operator Delete (void* pointee)
{
:: operator Delete (pointee);
}
............
};
x* px = new X ();

The new in the line code is new operator, which calls the operator new in class X, allocates space for objects of that class, and then calls the constructor of the current instance.

Delete px;

The delete in the line code is the delete operator, which calls the destructor of the instance, and then calls the operator delete in class X to free up the space occupied by the instance.

The behavior of the new operator and delete operator cannot and should not be changed, which is the commitment of the C + + standard. The operator new and the malloc in the operator delete and C languages correspond to free, which is responsible for allocating and releasing space only. However, the space allocated using operator new must be freed using the operator delete, not free, because they are registered differently for memory usage. The reverse is also the same.

You can overload operator new and operator Delete to achieve different requirements for memory management, but you cannot overload the new operator or delete operator to change their behavior.

When overloading operator new, you can provide additional parameters that, when you new an object, pass extra arguments in parentheses after the keyword new. such as the following classes

Class A
{
Public
............
Static void* operator new (size_t size, const string& example)
{
cout << example << Endl;
Return:: operator new (size);
}
............
};
* PA = new ("This'll be printed out in operator new") A ();

The new standard C + + allows a parameter named Nothrow to be passed in such a way that the exception is not thrown when the space allocated for the object fails, but instead returns 0 to accommodate the behavior of the old standard new. Like what

Class B {};
b* PB = new (Nothrow) B ();

Of course, this can only be for those classes that use the default operator new operator. For classes that have overloaded operator new (such as The X and a above), they cannot naturally enjoy the gift of C + + standards without declaring that they can accept nothrow parameters.

Six overloaded forms of operator new

When writing
p = new P ();
This code, in fact, has two steps, first allocating memory,
Class members are then initialized on top of the allocated memory.
The second step is to have the constructor completed, the first step is the work of the new function.
The global new has six overloaded forms,
void *operator New (std::size_t count)
throw (Std::bad_alloc); General version
void *operator New (std::size_t count,//compatible with the earlier version of new
Const std::nothrow_t&) throw (); Memory allocation failure does not throw an exception
void *operator New (std::size_t count, void *ptr) throw ();
Placement version
void *operator new[] (std::size_t count)//
throw (Std::bad_alloc);
void *operator new[] (std::size_t count,//
Const std::nothrow_t&) throw ();
void *operator new[] (std::size_t count, void *ptr) throw ();
So, the usage just now is an overloaded form of using the new function.
If the object of a is overloaded with the new function as a member function
will be called first.
Introduction to various new C + +
1.new T
The first new one is the simplest, calling the class (if overloaded) or the global operator new allocation space, and then using the
parameter of the column after the type to call the constructor, using the
New TypeName (initial_args_list). If there are no arguments, parentheses can generally be omitted. For example
int *p=new int;
int *p=new int (10);
int *p=new foo ("Hello");
To destroy by calling Delete:
Delete p;
2. New t[]
This new is used to create a dynamic array of objects that he calls the object's operator new[] to allocate memory (if
No, call operator new, search order Ibid., and then invoke the object's default constructor to initialize each object
Usage:
New Typename[num_of_objects];
For example
int *p= new INT[10];
Use operator delete[when destroying]
3.new () T and New () t[]
This is a new with parameter, this form of new will call operator new (Size_t,othertype) to allocate memory
The Othertype here is compatible with the type of the parameters in the new parentheses,
This syntax is commonly used in a particular address widget object, called placement new, if operator new
(size_t,void*) has been defined, usually the compiler has provided an implementation, including the <new> header file, which
The implementation simply returns the specified address of the parameter, so the new () operator is created on the address in parentheses
Object
It is important to note that the second argument is not necessarily a void*, a legitimate type that can be recognized by C + + overload
Mechanism to decide to call that operator new
Of course, we can provide our own operator new (Size_,type) to determine the behavior of new, such as
Char data[1000][sizeof (foo)];
Inline void* operator new (size_t, int n)
{
return data[n];
}
You can use this interesting syntax to create an object:
Foo *p=new (6) foo (); To create an object on the sixth cell of data
Yes, it's interesting.
The standard library also provides a nothrow implementation:
void* operator New (std::size_t, const std::nothrow_t&) throw ();
void* operator new[] (std::size_t, const std::nothrow_t&) throw ();
You can implement call new failure without throwing an exception
New (nothrow) int (10);
Nothrow is an example of std::nothrow_t
The object created by placement new cannot be destroyed directly by the delete, but rather calls the object's destructor function to destroy the
Like, as to how the memory of the object is handled, depends on the specific source of this memory
4. Operator new (size_t)
This operator allocates the memory of the size specified by the parameter and returns the first address, which can be overloaded for the custom class.
The method is to declare in the class and add
void *operator New (size_t size)
{
Allocates memory here and returns its address
}
The various operator new and operator deletes that are overloaded in the class, whether or not declared, are static properties
It is generally not necessary to call operator new directly unless the original memory is allocated directly (this is similar to C's malloc)
To invoke global operator in the case of a conflict plus:: Scope operators:
:: operator new (1000); Allocate 1000 bytes
The returned memory needs to be recycled, call the corresponding operator delete
5.operator new[] (size_t)
This is also allocated memory, is only specifically for the array, that is, new t[] This form, of course, when needed to
Explicit invocation of
6.operator New (size_t size, Othertype other_value)
And operator new[] (size_t size, Othertype other_value)
See the new () above
It should be emphasized that new is used to create objects and allocate memory, and its behavior is immutable and can be changed by various
operator new, we can implement our memory allocation scheme by overloading operator new.

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.