C + + operator new, delete

Source: Internet
Author: User

In the process of software development, it is often necessary to allocate and revoke the memory space dynamically, such as inserting and deleting nodes in the dynamic list.

new int;  //开辟一个存放整数的存储空间,返回一个指向该存储空间的地址(即指针)。new int(100); //指定该整数的初值为100new char[10]; //包含10个字符的空间new int[5][4]; //二维数组(5*4)float *p=new float(3.14159); //地址赋给指针变量p

The general format used by the new operator is
new type [initial value];//cannot specify an initial value when allocating array space with new. If space cannot be allocated properly due to insufficient memory, then new returns a null pointer null, which allows the user to determine whether the allocated space was successful based on the value of the pointer.
The general format used by the delete operator is
delete[] pointer variable;

delete p;delete [ ]pt; //在指针变量面前加一对方括号,表示对数组空间的操作。

Dynamic creation and release of objects
The object that is defined is static, and the space occupied by the object cannot be released at any time during the program's operation. For example, when a function defines an object, the object is freed only at the end of the function. But sometimes people want to set up objects when they need them, revoke them when they are not needed, and free up the memory space it occupies for other data to use. This can increase the utilization of memory space.

class Box{private:    int height;    int width;    int length;public:    Box();    Box(int,int,int);    ~Box();    Box(Box &b);    void volume();};new Box;           //动态建立一个对象Box *pt;             //定义一个指向Box对象的指针变量ptpt=new Box;      //在pt中存放了新建对象的起始地址pt-->height;       //调用对象的height成员pt-->volume();   //调用对象的volume函数Box *pt=new Box(12,15,18);//释放内存空间delete pt;

C + + operator new, delete

Related Article

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.