Introduction to new operator usage in C + +

Source: Internet
Author: User
Tags exception handling

New is a language structure in the C + + programming language that is used to dynamically allocate memory and initialize the allocated memory with a constructor.

The use of new is called the "new operator expression", and its internal implementation is divided into two steps:

Call the corresponding operator new () function to dynamically allocate memory. If operator new () cannot successfully obtain the memory, the New_handler function is called. If the New_handler function is not set or the New_handler fails to allocate enough memory, the Std::bad_alloc exception is thrown. The operator new () function called by the "new operator expression", find the rule by the name of C + +, first by name lookup (that is, ADL rule) that relies on the argument, in the interior of the data type T to which the memory is requested, in the namespace of the data type T definition, and if not found, The global:: operator new () function is called directly.

Initializes an object of the corresponding type on the dynamic memory block allocated to it and returns its first address. If an exception is thrown when the constructor is called to initialize the object, the operator delete () function is automatically called to release the memory that is already allocated.

Each new object that is fetched must be destructor with delete and free memory to avoid memory leaks.

The new operator expression is a language structure of C + + and cannot be overloaded. However, the user can overload the operator new () function.

2.new operator Expression

2.1 The normal new operator

Model

p = New TypeName;
p = New TypeName (init);
p = new Typename{init};
```

eg

"" C + +
int *p = new int;
int *p = new int (5);
int *p = new Int{5};//c++ 11
2.2 The new operator that generates an array of objects

Model

p = new Type[size];
p = new Type[size] {One, two, size};
eg

p = new Int[5];
p = new Int[5]{1, 2, 3, 4, 5};
2.3 New operator with position

Model

New (Expression-list) type (init);
Expression-list will be the end of the list of arguments for the operator new () function. This form of the new operator expression first calls the operator new (size_t,othertypelist) function to get the memory, and then executes the constructor on the object. The othertypelist here as the parameter list is compatible with the type of the argument list expression-list in the new parenthesis (that is, the formal parameter argument can match).

New operator with position, semantically including four use cases:

Directly gives the memory location of the object to be constructed;
Does not throw an exception if the memory allocation fails to return an empty pointer;
Custom, with other parameters of the memory allocator;
For debugging purposes, give the source file name and line number when a constructor call fails.
In the narrow sense, new with position is the first case. One of the reasons for using this placement new is that the user's program cannot invoke its constructor on a piece of memory (that is, the user's program cannot call the constructor explicitly), and the constructor must be called by the compiled system-generated code. The second reason is that the object may need to be placed on the memory address of a particular hardware, or on a shared memory address of a multiprocessor kernel.

When you release this object, you cannot call placement Delete, you should call the destructor directly, such as: Pobj->~classtype (), and then free the memory yourself.

#include <iostream>
using namespace Std;
int main (int argc, char* argv[]) {
Char buf[100];
int *p=new (BUF) int (101);
cout<<* (int*) buf<<endl;
return 0;
}

2.4 The new operator that guarantees that the exception is not thrown

When allocating memory fails, the standard behavior of the new operator is to throw a Std::bad_alloc exception. You can also let the new operator return a null pointer instead of throwing an exception when allocating memory fails. Where Nothrow is an example of std::nothrow_t.

p = new (nothrow) type (init);
p = new (nothrow) type[size];

2.5 The new operator expression for self-customizing parameters

The parameter of the new operator can be a list of any legitimate types. The overload mechanism of C + + decides to call that operator new.

New (Type_list) Type (init);
New (Type_list) type[size];

2.6 Delete operator with position

C + + cannot directly destructor an object without releasing its memory by using the with-position delete operator expression. Therefore, there are two ways for the destructor to be released when the object is constructed with a generalized position-new expression:

The first approach is to write a function directly, complete the destructor, free up memory operation.

3.operator new () function overload

3.1 Normal operator new (size_t size) function

The operator new function can be overloaded by each C + + class as a member function. It can also be used as a global function overload.

void * operator new (std::size_t) throw (Std::bad_alloc);
void operator Delete (void*) throw ();
If memory needs to be recycled, call the corresponding operator delete () function.

For example, in the second step of the new operator expression, if an exception is thrown when the constructor initializes the memory, the exception handling mechanism, when the stack expands (stack unwinding), reclaims the memory that was dynamically allocated in the first step of the new operator expression. The corresponding operator delete () function is automatically invoked.

operator new [] (size_t size) function in array form 3.2

void * operator new[] (std::size_t) throw (Std::bad_alloc);
void operator delete[] (void*) throw ();

3.3 With position operator new function void operator new (size_t,void)

The operator new (size_t,void*) function is used to call new operator with position. The C + + standard library has provided the implementation of the operator new (size_t,void*) function, including the <new> header file. This implementation simply returns the specified address of the parameter, and the new operator with the position invokes the constructor on the address to initialize the object.

Default placement versions of operator new.
Inline void* operator new (std::size_t, void* __p) throw () {return __p;}
Inline void* operator new[] (std::size_t, void* __p) throw () {return __p;}
Default Placement versions of operator delete.
inline void operator Delete (void*, void*) throw () {}
inline void operator delete[] (void*, void*) throw () {}
Disables the redefinition of these 4 functions. Because it's already an inline function for <new>. In use, you don't actually need to #include <new>

The corresponding placement delete function should only be invoked automatically when the placement new operator expression calls an exception-handling stack unwind operation when the constructor throws an exception in the second step.

3.5 operator new function that guarantees that no exception is thrown

C + + Standard library <new> also provides a nothrow implementation, users can write their own function substitution:

void* operator New (std::size_t, const std::nothrow_t&) throw ();
void* operator new[] (std::size_t, const std::nothrow_t&) throw ();
void operator Delete (void*, const std::nothrow_t&) throw ();
void operator delete[] (void*, const std::nothrow_t&) throw ();

3.6 operator new function of self-customization parameters

This function is called by the new operator of the custom parameter. needs to be defined by the user to determine the behavior when allocating memory.

operator new (Size_,type1, Type2, ...);
eg

char data[1000][sizeof (int)];

Inline void* operator new (size_t, int n); {
return data[n];
}
void Foo () {
int *p=new (6) Int (102); To create an integer object on the sixth cell of data
}


Placement new to place new

>void*operator new (std::size_t, void *);
void operator delete (void *, void *); This operator reconstructs an object on allocated memory because memory is not allocated, so you do not have to worry about allocation failures. The only job is to call the constructor. To include a <new> header file.

# include <new>
# include <iostream>
void Main ()
{using namespace std;
char * p = new (Nothrow) char [4];
if (p = = NULL)
{cout < < "Allocte Failed" < <endl;    Exit (-1); }
// ...
LONG * q = new (p) long (1000);
delete []p; Release p only, do not release with Q.
P and Q are just the same as the first address, and the objects you build can be of different types. The "place" space should be less than the original space, safekeeping. When "place new" exceeds the scope of the application, the debug version will hang up, but the release version can run without error!
The function of this operator is to stop worrying about allocation failures as long as the first assignment succeeds.

# include <new>
# include <iostream>
void Main ()
{using namespace std;
char * p = new (nothrow) char [100];
if (p = = NULL)
{cout < < "Allocte Failed" < <endl;    Exit (-1); }
LONG * q1 = new (P) long (100);
Use Q1 ...
int * q2 = new (p) int[100/sizeof (int)];
Use Q2 ...
ADT * q3 = new (P) adt[100/sizeof (ADT)];
Use Q3 and then release the object ...
delete []p; Frees only space and no longer destructors objects.
Note: Use this operator to construct an object or array, make sure to explicitly call the destructor, and not replace the destructor with delete because the placement new object is no longer the same size as the original space.
# include <new>
# include <iostream>
void Main ()
{using namespace std;
char * p = new (nothrow) Char [sizeof (ADT) +2];
if (p = = NULL)
{cout < < "Allocte Failed" < <endl;    Exit (-1); }
// ...
ADT * q = new (p) ADT;
// ...
Delete q; Error
Q-> Adt::~adt (); Explicit invocation of destructors, releasing objects only
delete []p; Finally, use the original pointer to release the memory.
The main purpose of placement new is to reuse a single memory space that has been successfully applied. This avoids the futility of the application failure and avoids the release after use.

Special attention is given to the delete that must not be invoked for placement new, because the new is just a place to use someone else to apply for it (just a tenant, not a homeowner.) Have no right to sell the house. Freeing memory is nothrow new, that is, to use the original pointer to free memory

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.