8. Learn about new and delete with different meanings

Source: Internet
Author: User

There are three main forms of new in C ++: new operator, operator new, placement new

The usage of the three is different. Pay attention to the differences:

New OPERATOR:

The new operator, like other operators in the C ++ language (such as +,-,->,:...), is built in the language and always accomplish the same thing,ProgramMembers cannot change their meaning. The following is a new usage:

String* PS =New String("Hazirguo");

Its main tasks include:

  1. Allocate enough memory to place certain types of objects. In the above example, allocate enough memory to place a String object.
  2. Call a constructor to initialize the allocated memory objects. In the above example, the constructor of the string class is called: string (const string & S );
  3. Returns the corresponding pointer. In the preceding example, the pointer to the New String object is returned.

Note: Like sizeof, new is a keyword in C ++. It is not a function and cannot be overloaded!

 

Operator New:

The first point of the task completed by the new operator above is to call the function to execute the memory allocation action. Similar to the function of the malloc () function in C language, you can reload or override this function to change its behavior, this is the function completed by operator new. It is usually declared:

 
Void*Operator New(Size_t size );

The size parameter indicates the size of the memory to be allocated. The return value of the function is void *, pointing to an original uninitialized memory.

This function can be overloaded, but the type of the first parameter must always be size_t. The global operator new has multiple reloads. You can also write your own reload functions as needed, such:

 
Int* Pnum =New Int(5 );// Use new operator
 
// Write an operator new reload to initialize the allocated memory.
 
Void*Operator New(Size_t size,IntN)
{
 
Void* TMP = ::Operator New(Size );// Allocate memory in a heavy load mode using the Global operator New Function
 
*Static_cast<Int*> (TMP) = N;
 
ReturnTMP;
 
}
 
// Call your own version of the overload Function
 
Int* Pnum =Static_cast<Int*>Operator New(Sizeof(Int), 5 );

Placement New:

placement new is an overloaded version of operator new:

  void  *  operator   New  (size_t size,  void  * location) 
{
  return  loaction; 
}

build and initialize a new object on an allocated original memory. Because it is meaningless to call constructor In the allocated memory space to initialize the object, placement new is used. Add the header file # include before use. The method is as follows:

 ctest * PT =  New  (p) ctest (...);  // call the ctest constructor in the memory pointed to by P to initialize the ctest object and return the pointer to the object.  

For example:
Char* Buffer =New Char[Sizeof("Hazirguo") + 1];// Allocate memory beforehand
String* PCH =New(Buffer)String("Hazirguo");// Initialize the object

Summary:

1. If you want to generate and stack an object, use new operator to not only complete memory allocation, but also call a constructor for the object.

2. If you only want to allocate memory and do not want any constructor to be called, call the new operator function.

3. If you want to construct an object in the allocated memory, use placement new.

Likewise, delete has similar usage:

Delete OPERATOR:

Corresponding to the release action of new operator, it can analyze the object referred to by the pointer and release the memory occupied by the object. For example:

String* PS =New String("Hazirguo");
...
DeletePS;// Delete operator is used.
// The function of completing the above sentence is similar to the following:CodeCompleted functions:
PS-> ~String();// 1. Call the dtor of the object
Operator Delete(PS );// 2. Release the memory occupied by the object

Operator delete:

The function that completes the memory release action. It is usually declared as follows:

Void Operator Delete(Void* Memorytobedeallocated );
If you only want to process the original uninitialized memory, you should avoid new operator and delete operator, call operator new to retrieve the memory and return it to the system with operator delete:
Void* Buffer =Operator New(50 *Sizeof(Char));// Allocate 50 char-type memory space without any ctor
...
Operator Delete(Buffer );// Release the allocated memory without any dtor

The completed functions are similar to those of the malloc and free functions in C.

Placement delete:

If placement new is used to generate objects in a memory block, delete operator should be avoided for that memory block. Because Delete operator calls operator Delete to release the memory, the objects contained in the memory are not originally allocated by operator new. After all, placement new only returns the pointer it accepts and does not know where the pointer comes from. Therefore, to offset the impact of the constructor of the object, the destructor of the object should be called directly.

Example:

The following example is from the network, which can explain the problem:

 
/*
 
In F1, the new operator acts like operator new and placement new in F2,
 
You can also use the method in F3 to achieve the same effect.
 
*/
 
 
 
# Include <New>
 
# Include <iostream>
 
Using NamespaceSTD;
 
 
 
ClassCtest
 
{
Public:
 
Ctest (Int_ X,Int_ Y)
 
{
 
X = _ x;
 
Y = _ y;
 
}
 
~ Ctest ()
 
{
 
X = 0;
 
Y = 0;
 
}
 
VoidTest (Char* Sz)
 
{
 
Printf ("% S: x = % d y = % d \ n", SZ, x, y );
 
}
 
IntX;
 
IntY;
 
};
 
 
 
 
 /* New operator & Delete operator */
 
 
 
VoidF1 ()
 
{
 
Ctest * PT =NewCtest (1, 1 );// New operator
 
 
 
Pt-> test ("F1");
 
 
 
DeletePT;// Delete Operator
 
}
 
 
 
/* Operator New + placement New & operator Delete + placement Delete */
 
 
VoidF2 ()
 
{
 
Void* P =Operator New(Sizeof(Ctest ));// Operator New: Memory Allocation
 
Ctest * PT =New(P) ctest (2, 2 );// Placement New: Constructor
 
 
 
Pt-> test ("F2");
 
 
 
Pt-> ~ Ctest ();// The Destructor must be displayed.
Operator Delete(PT );// Operator Delete: releases the memory.
 
}
 
 
 
 
 
/* Also can implement like this */
 
 
 
VoidF3 ()
 
{
 
Char* P =New Char[Sizeof(Ctest)];// New operator: Char is of the built-in type and does not call constructor. It is equivalent to allocating only memory.
 
Ctest * PT =New(P) ctest (3, 3 );// Placement New: Construct the ctest object on the memory.
 
 
Pt-> test ("F3");
 
 
 
Pt-> ~ Ctest ();// The Destructor ctest object must be displayed.
 
Delete[] P;// Delete OPERATOR: Char is of the built-in type and does not call the destructor. It is equivalent to releasing only the memory.
 
}
 
 
 
VoidMain ()
 
{
 
F1 ();
 
F2 ();
 
F3 ();
 
}

The previous steps are for single objects. When Facing arrays, you need to pay attention to some forms, such:

String* PS =New String[10];// Allocate an object Array
In this case, the memory allocation is no longer the responsibility of operator new, but the function named operator new [], but this function can also be overloaded.
(... To be supplemented here)
 
 
 
References: more than 35 effective methods for programming and design

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.