[C + + space allocation]new operator, operator new, placement new are different from contact

Source: Internet
Author: User

First Science:

1. New's execution process:

(1) Request memory via operator new

(2) Call the constructor with placement new (the built-in type ignores this step)

(3) Return memory pointer

2. Comparison of new and malloc:

(1) The New_handler handler function is called when new fails, and malloc does not return null on failure

(2) New can automatically invoke the constructor of an object via placement new, and malloc will not

(3) New comes out of the belt type, malloc is void*, need to cast

(4) New is C + + operator, malloc is C standard library function

3. The execution of the delete process:

(1) Call destructor (built-in type ignores this step)

(2) Releasing memory

Comparison of 4.delete and free

(1) Delete can automatically call the object's destructor, and malloc will not

(2) Delete is C + + operator, free is C standard library function

New Operator/delete operator is the new and delete operators, and operator New/operator Delete is a function.

New operator
(1) Call operator new to allocate enough space and call the constructor of the related object
(2) can not be overloaded

operator NEW
(1) Only the required space is allocated, and the constructor of the related object is not called. When the required allocated space is not met, the
-If there is new_handler, call New_handler, otherwise
-If no exception is required (expressed in the nothrow parameter), the BAD_ALLOC exception is executed, otherwise
--Return 0
(2) can be overloaded
(3) When overloading, the return type must be declared as void*
(4) When overloading, the first parameter type must be the size (in bytes) of the allocation space for the expression requirement, type size_t
(5) When overloading, can take other parameters

Delete is similar to delete operator

#include <iostream> #include <string>using namespace Std;class x{public:    X () {cout<< " Constructor of X "<<endl; }    ~x () {cout<< "destructor of X" <<ENDL;}    void* operator new (size_t size,string str)    {        cout<< "operator new size" <<size<< "with string" <<str<<endl;        Return:: operator new (size);//Call global operator new application space    }    void operator delete (void* pointee)    {        cout< < "operator delete" <<endl;        :: operator delete (pointee);//Call global operator Delete to free up space    }private:    int num;}; int main () {    x *px = new ("A new Class") x;    Delete px;    return 0;}

Note: operator new is a global function with three of these functions, one of which is Placemet new, which is said later. The general user does not (although can) overload the operator new function globally, but instead overloads the operator new function in a custom class. operator new is a request for an object's space memory, so the call size_t omitted, but for operator new[] This function, to explicitly explain the number of objects in the array.

Both the new and delete operators are used, and they are applied and freed from the memory in the heap, which cannot be overloaded. To implement different memory allocation behaviors, you need to overload operator new and operator delete instead of new and delete.

Operator new is like operator+, which can be overloaded. However, it is not possible to overload the prototype with the operator new (size_t size) in the global, which can only be overloaded in the class. If operator new is not overloaded in the class, then the call is global: operator new to complete the heap allocation. Similarly, operator new[], operator delete, operator delete[] can also be overloaded.

As for placement new, it's just an overloaded version of operator new, but we seldom use it. If you want to create an object in an already allocated memory, it won't work when you use new. In other words, placement new allows you to construct a new object in an already allocated memory (stack or heap). The void*p in the prototype is actually the first address that points to an already allocated memory buffer.

We know that allocating memory using the new operator requires finding enough free space in the heap, which is slow, and there is the possibility of an exception (not enough space) to allocate memory. Placement new can solve this problem. We construct objects in a pre-prepared memory buffer, do not need to find memory, memory allocation time is constant. And will not appear in the middle of the program run out of memory exceptions. Therefore, placement new is ideal for applications that do not want to be interrupted for long periods of time. Placement new uses the following methods:

1. Buffer is allocated in advance, you can use the heap space, or you can use the stack space. So there are two ways to allocate: Class MyClass {...}; Char *buf = new char[n * sizeof (MYCLASS)];char buf[n * sizeof (MyClass)];2. The construction of the object MyClass * pClass = new (BUF) MyClass; Use placement NEW3. Object destruction Once this object is used, you must explicitly call the class's destructor to destroy the object. However, the memory space is not freed so that other objects are constructed. Pclass->~myclass (); 4. Memory is freed if the buffer is in the heap, then call delete[] buf for memory release. If it is in the stack, then it is valid within its scope, out of scope, and memory is automatically freed. Additional note: In the C + + standard, for placement operator new [] like the following description: placement operator new[] needs implementation-defined amount of Additional storage to save a size of array. So we have to apply more than the size of the original object, sizeof (int) bytes to hold the number of objects, or the size of the array. How to use the new in the second step is to use placement new, but it does not apply for memory, just call the constructor. Returns a pointer to an already allocated memory, so the object does not need to call Delete to free space when it is destroyed, but the destructor must be called to destroy the object. So for placement new for an array of objects: Char *buf=new char[n*sizeof (MyClass) +sizeof (int)];char buf[n*sizeof (MyClass) +sizeof (int )]; MyClass * Pclass=new (BUF) myclass[n]; Use placement new[]

In front of the world there are three operator new functions, see below:

Operator new is divided into three forms (the first 2 do not call constructors, which differs from new operator):

1:void* operator new (std::size_t size) throw (std::bad_alloc); 2:void* operator new (std::size_t size, const STD::NOTHRO W_t & nothrow_constant) throw (), 3:void* operator new (std::size_t size, void* ptr) throw ();

The first allocates a storage space of size bytes, and the object type is memory-aligned. If successful, returns a non-null pointer to the first address. Failed to throw Bad_alloc exception.

The second type does not throw an exception when the allocation fails, it returns a null pointer.

The third type is the placement new version. It does not allocate memory, calls the appropriate constructor to construct an object where PTR refers, and then returns the argument pointer ptr.

Three versions of operator new are defined in the global namespace, not in Std. The first and second versions of C + + are declared by default in each compilation unit and do not require # include <new> header files. The first and second versions can be replaced and overloaded by the user (typically overloaded in a class), define their own version, and the third placement new cannot be overloaded.

operator new Example#include <iostream> #include <new>using namespace std; struct MyClass {MyClass () {cout << "MyClass constructed\n";}}; int main () {    int * p1 = new int;//same as://int * p1 = (int*) operator new (sizeof (int));    int * P2 = new (nothrow) int;//same as://int * P2 = (int*) operator new (sizeof (int), nothrow);    MyClass * P3 = (myclass*) operator new (sizeof (MyClass));//(!) not the same as://myclass * p3 = new myclass;//(Construc Tor not called by function call, even for non-pod types)    new (p3) MyClass;   Calls constructor//same as://operator new (sizeof (MyClass), p3)    return 0;} Result output: MyClass constructed

  

[C + + space allocation]new operator, operator new, placement new are different from contact

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.