In C + +:: operator new,:: operator delete

Source: Internet
Author: User
Tags prototype definition

In general, when using new and delete, two things are done, one is the configuration of the space (new is the allocation, the delete is the recycle), but the destructor of the calling object

But there are ways to separate the two processes.

That is explicit invocation:: operator new,:: operator delete, they are only spatially configured, do not call the object's destructor

See the following example for details:

//Operator new[] Example#include <iostream>//Std::cout#include <new>//:: operator new[]structMyClass {intData MyClass () {std::cout <<‘*‘;}//Print an asterisk for each construction};intMain () {std::cout <<"constructions (1): ";//Allocates and constructs five objects:MyClass * P1 =newMYCLASS[5]; Std::cout <<‘\n‘; Std::cout <<"constructions (2): ";//Allocates and constructs five objects (nothrow):MyClass * P2 =new(Std::nothrow)  MYCLASS[5]; Std::cout <<‘\n‘; Std::cout <<"constructions (3): ";//Allocates storage for five objects, but does not construct them:MyClass * P3 =static_cast<MyClass*> (::operator new(sizeof(Myclass[5])); Std::cout <<‘\n‘; Std::cout <<"constructions (4): ";//Constructs five objects at P3, but does not allocate:  new(p3)  MYCLASS[5]; Std::cout <<‘\n‘;delete[] P3;delete[] P2;delete[] P1;return0;}
Edit & Run

For operator delete and operator new, you can see the prototype definition here:

Http://en.cppreference.com/w/cpp/memory/new/operator_delete

Http://en.cppreference.com/w/cpp/memory/new/operator_new

As you can see, they are all void*-type pointers, almost like the malloc free mechanism in the C language.

In C + +:: operator new,:: operator delete

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.