Detailed explanation of the use of the new and delete operators in C + + _c language

Source: Internet
Author: User

C + + supports dynamic allocation and release of objects using the new and delete operators. These operators allocate memory for objects from a pool called free storage. The new operator calls the special function operator New,delete operator to call a special function operator delete.
In Visual C + +. NET 2002, the new feature in the standard C + + library will support the behavior specified in the C + + standard and throw a Std::bad_alloc exception if the memory allocation fails.
If the memory allocation fails, the C run-time Library's new function also throws a Std::bad_alloc exception.
If you still need a nothrownew.obj version of new for the C run-time Library, link your program to the database. However, when you link to nothrownew.obj, new in the standard C + + library will no longer work.

Calling the new operator
when you encounter the following statement in your program, it is converted to a call to the function operator NEW:

Char *pch = new Char[buffer_size];

If the request is for 0-byte storage, operator new returns a pointer to a different object (that is, a duplicate call to operator new will return a different pointer). If the allocation request does not have enough memory, operator new returns NULL or throws an exception (see for more information).
You can write routines that attempt to free memory and try the assignment again; For more information, see _set_new_handler. For more detailed information about recovery scenarios, see the following topics: handling out-of-memory conditions.
The two ranges of the operator new function are described in the following table.
Operator the scope of the new function

operator Range
:: operator NEW Global
Class-name:: operator new Class

The type of the first parameter of operator new must be size_t (the type defined in STDDEF.H), and the return type is always void *.
The global operator new function is invoked when an object with a built-in type is assigned with the new operator, an object with a class type that does not contain a user-defined operator new function, and any type of array. When you use the new operator to assign an object of a class type (where operator new is defined), the operator new for that class is invoked.
The operator new function defined for a class is a static member function (therefore, it cannot be a virtual function) that hides the global operator new function of objects of this class type. Consider the case where new is used to allocate memory and set memory to a given value:

Spec1_the_operator_new_function1.cpp
#include <malloc.h>
#include <memory.h>

class Blanks
{public
:
 blanks () {}
 void *operator new (size_t stallocateblock, Char chinit);
void *blanks::operator New (size_t stallocateblock, char chinit)
{
 void *pvtemp = malloc (stallocateblock); 
   if (pvtemp!= 0)
  memset (pvtemp, Chinit, stallocateblock);
 return pvtemp;
}
For discrete objects of type blanks, the global operator new function
/be hidden. Therefore, the following code allocates an object of type
//blanks and initializes it to 0xa5
int main ()
{
 Blanks *a5 = new (0XA5) blanks;
 return A5!= 0;
}

The arguments supplied to new with parentheses are passed to Chinit as the blanks::operator new argument. However, the global operator new function is hidden, causing the following code to generate an error:

Blanks *someblanks = new Blanks;

In Visual C + + 5.0 and earlier versions, the global operator new function is always used by the non-class type and all arrays that are assigned with the new operator, regardless of whether the type is class or not.
Starting with Visual C + + 5.0, the compiler supports the member array new and delete operators in class declarations. For example:

Spec1_the_operator_new_function2.cpp
class MyClass
{public
:
 void * operator new[] (size_t)
 { return
  0;
 }
 void operator delete[] (void*)
 {
 }
};

int main () 
{
 MyClass *pmyclass = new Myclass[5];
 delete [] pmyclass;
}

Insufficient processing memory
testing for failed memory allocations can be done with the following encoding:

Insufficient_memory_conditions.cpp
//compile with:/EHsc
#include <iostream>
using namespace Std;
#define BIG_NUMBER 100000000
int main () {
 int *pi = new Int[big_number];
 if (PI = = 0x0) {
  cout << "Insufficient memory" << Endl;
  Return-1
 }
}

Other ways to handle failed memory allocation requirements: Write a custom recovery routine to handle this type of failure, and then register your function by calling the _set_new_handler run-time function.
delete operator
You can use the delete operator to release memory that is dynamically allocated using the new operator. The delete operator calls the operator delete function, which releases the memory back to the available pool. Using the delete operator also causes the class destructor, if any, to be invoked.
There are global and class-scoped operator delete functions. You can define only one operator delete function for a given class, and if this function is defined, it hides the global operator delete function. The global operator delete function is always called for all types of arrays.
The global operator delete function (if declared) takes a single parameter of the void * type, which contains a pointer to the object to be freed. The return type is void (operator delete cannot return a value). There are two forms of a class member operator the DELETE function:

void operator delete (void *);
void operator delete (void *, size_t);

Only one of the preceding two variables exists in the given class. The first form runs as described by the global operator delete. The second form takes two parameters, the first is a pointer to the memory block to be freed, and the second is the number of bytes to be freed. The second form is particularly useful when the operator delete function in the base class is used to remove objects from derived classes.
The operator delete function is static, so it cannot be a virtual function. The operator delete function is subject to access control, as described in member access control.
The following example shows the user-defined operator new AND operator delete functions designed to record allocations and releases of memory:

Spec1_the_operator_delete_function1.cpp//compile with:/EHSC//Arguments:3 #include <iostream> using Namespa

CE std;  int flogmemory = 0;
Perform logging (0=no; nonzero=yes)? int cblocksallocated = 0;

Count of blocks allocated.
user-defined operator New.

 void *operator New (size_t stallocateblock) {static int finopnew = 0;//Guard flag.
  if (flogmemory &&!finopnew) {finopnew = 1; Clog << "Memory blocks" << ++cblocksallocated << "allocated for" << Stallocateblock &LT;&L T
  "Bytes\n";
 finopnew = 0;
return malloc (Stallocateblock);
}//user-defined operator delete.
 void operator delete (void *pvmem) {static int finopdelete = 0;//Guard flag.
  if (flogmemory &&!finopdelete) {finopdelete = 1;
  Clog << "Memory block" << cblocksallocated--<< "deallocated\n";
 Finopdelete = 0;
Free (PVMEM); int main (int argc, char *argv[]) {flogmemory = 1;//Turn Logging on if (argc > 1) for (int i = 0; i < atoi (argv[1]); ++i) {char *pmem = new CHAR[10];
  Delete[] Pmem; } flogmemory = 0;
 Turn logging off.
return cblocksallocated;

 }

The preceding code can be used to detect "memory overflow", a memory that is allocated in free storage but has never been freed. To perform this detection, you should redefine the global new and delete operators to calculate the allocation and release of memory.
Starting with Visual C + + 5.0, the compiler supports the member array new and delete operators in class declarations. For example:

Spec1_the_operator_delete_function2.cpp
//compile with:/C
class X {public
:
 void * operator new[] ( size_t) {return
  0;
 }
 void operator delete[] (void*) {}
};

void F () {
 X *px = new X[5];
 delete [] PX;
}

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.