Inside of the new operator in C + +: new operator, operator new, placement new

Source: Internet
Author: User

Original link one, new operator (new operator)

People sometimes seem to like the benefits of making the C + + language difficult to understand. Let's say the difference between the new operator (new operator) and operator new.

When you write this code:

String *ps = new String ("Memory Management");
The new you are using is new operator

This operator, like sizeof, is a language built-in. You can't change the meaning of it, its function is always the same. The function to be finished is divided into two parts. The first part is to allocate enough memory to accommodate the object of the desired type.

The second part is that it calls the constructor to initialize the in-memory object. The new operator always does both things, and you cannot change its behavior in any way whatsoever.
(the summary is that thenew operator does two things, allocating memory + calling constructor initialization.)

You can't change the way it behaves. )

Second, operator new

What you can change is how to allocate memory for an object .

The new operator calls a function to complete the required memory allocation, and you can override or reload the function to change its behavior. the name of the function called by the new operator for allocating memory is operator new.

The function operator new usually declares this:

void * operator new (size_t size);
The return value type is void* because the function returns an unprocessed (raw) pointer. Uninitialized memory. (Suppose you like it.) You can write a operator new function that initializes memory to store some values before returning a pointer, but generally does not.

The number of parameters size_t determines how much memory is allocated.

You can add an additional parameter overload function operator new, but the first parameter type must be size_t.

(For more information about operator new, see effective C + + clause 8 to clause 10.) )

You don't normally call operator new, but once you do. You can invoke it like any other function:

void *rawmemory = operator new (sizeof (string));
The operator operator new returns a pointer to a piece of memory sufficient to hold a string object.

Just like malloc, operator New's responsibility is simply to allocate memory.

It has no knowledge of the constructor function. Operator new is aware of memory allocations. Passing an unhandled pointer returned by operator new to an object is the work of the new operator. When your compiler encounters this statement:

String *ps = new String ("Memory Management");
It generates code that is more or less similar to the following code (see effective C + + clause 8 and clause 10 for many other details). And my article counting the gaze in object. ):
<pre name = "code" class = "cpp"> void * memory = operator new (sizeof (string)); // Get unprocessed memory as a String object
call string :: string ("Memory Management")
on * memory; // objects in memory

string * ps = static_cast <string *> (memory); // make the ps pointer point to the new object

Note that the second step involves calling the constructor, which you do as a program ape is forbidden to do so. Your compiler does not have this constraint, it can do everything it wants to do.

So if you want to build a heap object you have to use the new operator. Constructors cannot be called directly to initialize an object. ( Summary: operator new is a function for allocating memory, called for the new operator.) can be overloaded (with restrictions))

Third, placement new

Sometimes you do want to call the constructor directly. It is meaningless to call a constructor on an existing object because the constructor is used to initialize the object. An object can only be initialized once when it is given its initial value.

But sometimes you have some allocated (raw) memory that you have already assigned but you need to construct an object in these memory . You can use a special operator new , which is called placement new.

The following example is how placement new is used, considering:

class Widget {
  Widget(int widgetSize);

Widget * constructWidgetInBuffer(void *buffer,int widgetSize)
 return new (buffer) Widget(widgetSize);
This function returns a pointer. Points to a Widget object, which is assigned in the buffer that is forwarded to the function.

This function may be useful when a program uses shared memory or memory-mapped I/O, because in such a program the object must be placed on a certain address or in memory allocated by the routine. (see clause 4, a non-identical example of how to use placement new.) )

Inside the Constructwidgetinbuffer. The returned expression is: New (buffer) Widget (widgetsize)

This may seem strange at first, but it is a use of the new operator and requires an extra variable (buffer). When the new operator implicitly calls the operator new function. Pass this variable to it. The called operator new function must also accept the void* pointer parameter in addition to the mandatory parameter size_t. Points to the memory space occupied by the construction object. This operator new is placement new, which looks like this:

void * operator new(size_t, void *location)
 return location;
This may be easier than you expect, but that's what placement new needs to do. After all, the purpose of operator new is to allocate memory for an object and then return a pointer to that memory. In the case of placement new, the caller has obtained a pointer to memory. Because the caller knows where the object should be placed. What placement new has to do is return the pointer to it. (No practical (but mandatory) parameter size_t has no name to prevent the compiler from issuing a warning that it is not being used. See clause 6.

Placement new is part of the standard C + + library. In order to use placement new. You must use the statement # include <new> (or assume that your compiler does not yet support this new style header file name).

( Summary: Placement New is a special operator new, used for a piece of raw memory that has been allocated but not processed or initialized )

Iv. Summary

Let's come back from placement new for a moment and see the new operator (new operator) with operator New, (the new operator calls operator new)

    • You want to build an object on the heap, you should use the new operator. It allocates both memory and calls constructors for objects.
    • Assuming you only want to allocate memory, you should call the operator new function; it does not call the constructor.
    • Suppose you want to customize your own memory allocation process when the heap object is built, you should write your own operator new function. Then using the new operator, the new operator will invoke your custom operator new.
    • Suppose you want to create an object in a piece of memory that has been given a pointer. should use placement new.

V. Deletion and Memory deallocation

To avoid memory leaks, each dynamic memory allocation must correspond to a deallocation equivalent to the opposite.

The relationship between the function operator delete and the delete operator is the same as the relationship of operator new with the new operator . When you see the code:

String *ps;...delete PS; Using the delete operator
Your compiler generates code to deconstruct the object and release the memory that the object occupies.

Operator Delete is used to free memory. It is declared like this:

void operator delete (void *memorytobedeallocated);
Therefore, delete PS; Causes the compiler to generate similar code:
ps->~string(); // call the object‘s dtor
operator delete(ps); // deallocate the memory the object occupied
One implication of this is that if you just want to handle uninitialized memory, you should bypass the new and delete operators, and call operator new to get the memory and operator delete to release the memory to the system:
void * buffer = operator new (50 * sizeof (char)); // allocate enough memory to hold 50 chars

// did not call the constructor

operator delete (buffer); // release memory

// did not call the destructor

This is equivalent to calling malloc and free in C.

How is the object created by 2.placement new released?

Suppose you create an object in memory with placement new, you should avoid using the delete operator in that memory.

Because the delete operator calls operator delete to free memory, the memory that includes the object is not originally allocated by operator new. Placement new is simply the return of the pointer that is forwarded to it. Who knows where this pointer comes from? Instead, you should explicitly call the object's destructor to remove the effect of the constructor:

// Functions that allocate and release memory in shared memory void * mallocShared (size_t size);

void freeShared (void * memory);
void * sharedMemory = mallocShared (sizeof (Widget));
Widget * pw = // As seen above,
constructWidgetInBuffer (sharedMemory, 10); // use

// placement new

delete pw; // The result is uncertain! The shared memory comes from
// mallocShared, not operator new

pw-> ~ Widget (); // Correct. Destructs the widget pointed to by pw,

// but not released
// Include Widget's memory

freeShared (pw); // Correct. Release the shared memory pointed to by pw

// but the destructor is not called
As you can see from the example above, assuming that the raw memory passed to placement new is allocated dynamically (through some infrequently used methods), suppose you want to avoid a memory leak, you must release it. (See my article counting objects's gaze on placement delete.) )

Six, array

Everything went well so far. But we still have to go.

So far, all we've tried to do is build one object at a time.

How do I allocate an array? What's going to happen?

string *ps = new string[10]; // allocate an array of objects

The new operator is still used, but the behavior of the new operator is slightly different from the creation of a single object when an array is created.

The first is that memory is no longer allocated with operator new, instead of an equivalent array allocation function called operator new[] (often referred to as array new).

It can be overloaded like operator new.

This will allow you to control the memory allocation of the array. Just as you can control the memory allocations of individual objects (but there are some restrictive instructions, see effective C + + clause 8).

(operator new[] is a relatively new thing for C + +. So your compiler might not support it. Suppose it is not supported. Whatever the object type is in the array. Global operator new will be used to allocate memory for each array.

It is difficult to customize the array memory allocation under this compiler. Because it needs to rewrite the global operator new. This is not an easy task to accept.

By default, all dynamic memory allocations in the global operator new handler, so any change in its behavior will have a deep and pervasive impact. and the global operator new has a normal signature (normal signature) (also a single parameter size_t. See effective C + + clause 9). So suppose you decide to declare it in your own way, and you immediately make your program incompatible with other libraries based on these considerations, an array of custom memory management is not a reasonable design in a compiler that lacks operator new[] support. )

The second difference is the number of constructors that the new operator calls. For arrays, the constructors for each object in the array must be called:

string * ps = new string [10]; // call operator new [] to allocate memory for 10 string objects,

// Then call the default constructor of the string object for each array element.
Same when the delete operator is used for an array, it calls the destructor for each array element and then calls operator delete to free up memory. (buxizhizhou530 Note: This should be operator delete[]

Just as you can replace or reload operator delete, you also replace or reload operator delete[].

There are some limitations on the methods that they overload.

Please refer to the excellent C + + textbook.

(Summary: Array, two different points, one-time call operator new[] function, the second is the new operator called the number of constructors is different. )

Vii. Summary
The new and delete operators are built-in, and their behavior is not controlled by you. The memory allocations and deallocation functions that they invoke can be controlled. When you want to customize the behavior of the new and delete operators, keep in mind that you can't really do that. You can only change the way they are used to complete their function, and the finished function is fixed by the language. cannot be changed. (Can modify how they does what they does, but what they does is fixed by the language)

References: Delete in C + +, new and new [], delete[] operator insider

This article most of the content from the above blog, unfortunately this blog is reproduced, did not find the original source. This article is only based on the above blog content, plus their own understanding, has been another typesetting, color labeling, related changes, and their own summary.

Hypothetical error. Welcome to Exchange ~


Additional additions to new, operator new, and placement new in C + +

Placement new operator (Classic) in C + + is general. can be viewed slightly

Inside the new operator in

C + +: new operator, operator new, placement new

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: 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.