C + + new (2)

Source: Internet
Author: User

1. New AND operator new

There are many syntaxes in C + + that are difficult to understand, such as the difference between the new operator (operator, the same) and operator new, which is exactly the difference between new and operator new.

1.1 New operator

The following code:

String *ps=new string ("Memory Management");

The new that is used here is the so-called new operator, built in the C + + language, like sizeof, that doesn't change meaning and always does the same thing.

The meaning of this action is divided into two aspects:

First, it allocates enough memory to be used to place objects of a certain type . For the above example, it allocates enough memory to place a string object.

Second, it calls a constructor that sets the initial value for that object in the memory that was just allocated.

New operator always do these two things, and you can't change their behavior anyway.

1.2 Operator NEW

What can be changed is the allocation of the memory that is used to hold the object ,new operator calls a function, performs the necessary memory allocation action, and you can override or reload that function to change its behavior. This function name is called operator new.

The function operator new is usually declared as follows:

void * operator new (size_t size);

Its return type void*. That is , returns a pointer to a piece of raw memory with no initial value set .

The size_t parameter in the function indicates how much memory needs to be allocated, you can overload the operator new, plus additional parameters, but the first parameter type must always be size_t.

Or you've never used operator new directly, but you can call it just like any other function .

void* rawmemory=operator New (sizeof (string));

Operator new here returns a pointer to a block of memory sufficient to hold a string object.

Like malloc, the only task for operator new is to allocate memory, which does not know what a constructor is, it is only responsible for allocating memory.

It is the responsibility of new operator to get the memory that operator new returns and convert it to an object.

1.3 When the compiler sees this sentence:

String *ps=new string ("Memory Management");

It must produce some code that will more or less reflect the following behavior:

1) void* Memory=operator New (sizeof (string)); Gets the raw memory used to place a string object

2) Call String::string ("Memory Management") on *memory;// initializes the in-memory object

3) string *ps=static_cast<string*> (memory); Let PS point to the newly completed object

Note The second step, call a constructor. As programmers do not have the right to bypass the new operator like this using constructors, but the compiler does so .

That's why if you want to make a heap-based object, be sure to use the new operator.

This means that everything new comes out in the heap, and cannot directly invoke the constructor required for object initialization.

2. Placement NEW

2.1 Sometimes you really want to call a constructor directly, calling its constructor for an already existing object, because the constructor is used for object initialization, and the object can only be initialized once. but you occasionally have some raw memory allocated, you need to build the object on it, there is a special place operator new called placement new, allowing to do so.

For example:

Class Widget {public:widget (int widgetsize); ...... };

widget* constructwidgetinbuffer (void *buffer,int size) {return new (buffer) Widget (size); }

This function returns a pointer to a Widget object, which is constructed on a memory buffer that is passed to this function . When the program runs to shared memory or memory I/O mappings. This type of function can be useful because, in that case, the object must be placed at a specific address, or in memory allocated by a special function.

2.2 Internal function

Widget* Constructwidgetinbuffer has only one expression new (buffer) Widget (size),

It's a little strange, in fact, that this is one of the usages of new operator, specifying an additional argument (buffer) as the new operator "implicitly call operator new". The called operator new, in addition to accepting "must have size_t arguments", also accepts a void* parameter, pointing to a piece of memory, ready to accept the constructed object . such operator new is the so-called placement new :

void * operator new (size_t size,void* location)

{

return location;

}

The purpose of operator new is to find a piece of memory for the object and then return a pointer to it, in the case of placement new, the caller already knows the pointer to the memory because the caller knows where the object should be placed. So the only thing placement new needs to do is return the pointer it gets.

As for the size_t parameter, which is not used (but must have), the name is not given in order to avoid the "compiler something is not used" warning.

Note also : Placement New is part of the C + + standard library and is used to use the placement new #include <new> the old compiler #include <new.h >

Looking back at placement new, we can understand the relationship between new operator and operator new.

The two terms are seemingly confusing, but in fact they are well understood:

1) If you want to generate the object in the heap, it is new operator, which not only allocates memory but calls a constructor for that object.

2) If you are only planning to allocate memory , use operator new, there is no constructor called.

3) If you intend to generate your own decision on the memory allocation method in the heap object , please write your own operator new. and using new operator, it will automatically invoke the operator new you wrote.

4) If you intend to construct the object in memory that has been assigned (and has pointers) , use placement new.

3. Delete and memory release

To avoid resource leaks, each dynamic allocation behavior must match a corresponding release action.

The 3.1 function operator delete for the built-in delete operator (operator) is like operator new for new operator.

String *ps;

...

Delete PS; Use delete operator.

The memory release action is performed by operator delete , which is usually declared as follows:

void operator Delete (void* memorytobedeallocated);

Therefore, delete PS causes the compiler code to be as follows:

1) ps->~string ();//Call destructor

2) operator Delete (PS);//Release the memory occupied by the object

3.2 It is suggested here that the new operator and delete operator should be completely avoided if only the original, non-initial memory is intended to be processed. Instead, call operator new to get the memory and return the system with operator delete.

For example:

void* buffer=operator New (50*sizeof (char));//Allocate memory, place 50 char, no call constructor

...

operator delete (buffer); frees the memory without calling the destructor directly.

This group behaves like malloc and free.

3.3 Placement New

If you use placement new to produce an object in a block of memory, you should avoid using the delete operator (operator) for that block of memory.

Because delete operator calls operator delete to free memory, the memory contains objects that were not originally assigned by operator new. Placement new just returns the pointer it receives, who knows where the pointer comes from?

Therefore, in order to counteract the effect of the object's constructor, the destructor of the object should be called directly when using placement new.

For example:

void * mallocshared (size_t size);//request to allocate memory

void freeshared (void * momery);//Free memory

void* sharedmemory=mallocshared (sizeof (Widget));

Widget *pw=constructwidgetbuffer (sharedmemory,10);//Use the placement new of the previous widget class

...

Delete pw;//is undefined because sharedmemory comes from mallocshared, not from new.

Pw->~widget ();//ok, destructors the Widget object referred to by PW, but does not release the memory occupied by the widget.

freeshared (PW);//ok, releases the memory referred to by PW, without invoking any destructors.

As shown above, if the raw memory that is given to placement new is dynamically allocated, then the memory will eventually be freed to avoid leak.

4. Dynamically allocated arrays (Arrays)

What is done above is based on a single object, what if it is a group of objects?

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

4.1 Here new is similar to the previous new behavior, but slightly different, where you can no longer allocate memory operator new, but rather operator New[] is responsible for allocation .

Like operator new, operator new[] can also be overloaded.

Note: operator new[] is a feature of C + + that is quite late, so your compiler may not necessarily support it. If so, the global operator new is used to allocate memory for each array (regardless of the type of object in the array). Customizing the array memory allocation behavior under such a compiler is difficult because you have to rewrite the global operator new. By default, the global version of operator New is responsible for all dynamic memory allocations in the program, so any change in its behavior can have a global impact.

Also, as mentioned earlier, operator new allows only one parameter to be size_t. So if you decide to declare your own function, your program is incompatible with any library that makes the same decision.

In many ways, if the compiler does not support operator new[], customizing the array memory management behavior is not a sensible decision.

The new of the 4.2 array is different from the constructor called by new for the single object, and the new array must call a constructor for each object in the array.

String *ps=new string[10];// calls operator new[] to allocate enough memory to hold 10 string objects, and then invokes the default constructor for string for each element.

Similarly, when delete is used, it also calls the destructor for each element in the array and then calls operator delete[] to free memory.

For example, delete []ps;// calls the string destructor for each element in the array and then calls operator delete[] to free memory . (The destructor is called first, and then the memory is freed.) )

As with operator delete operator delete[] can also be overloaded.

Finally, thenew and delete are built-in operators and the language itself is fixed and cannot be re-customized. But it calls the memory allocation/deallocation function, i.e. operator new and operator delete can be overloaded.

Reprinted from: http://www.cnblogs.com/fly1988happy/archive/2012/04/26/2471099.html

C + + new (2)

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.