The difference between using new and creating an object without using new in C + +

Source: Internet
Author: User
Tags class definition
First, new Create class object and not new difference

Here are some of the features you have summed up about the new Create class object:

  • New Create class object requires pointer reception, one initialization, multiple use
  • New Create class object with delete destroy required
  • The new creation object uses heap space directly, while local without new definition class object uses stack space
  • New object pointers are used for a wide variety of purposes, such as function return values, function parameters, etc.
  • Frequent invocation is not suitable for new, just as new applies and frees memory
Second, new Create class object instance 1, new Create class object example:

ctest* pTest = new CTest ();

Delete pTest;

The ptest is used to receive class object pointers.

Use the class definition declaration directly without NEW:

CTest Mtest;

This method of creation does not need to be released manually after use, and the class destructor is executed automatically. In the case of new applications, the destructor is executed only when the call to delete occurs, and a memory leak is caused if the program exits without executing the delete.

2. Define class pointers only

This is quite different from not using the new declaration object, the class pointer can be defined first, but the class pointer is just a generic pointer, before new and allocates any memory space for the class object. Like what:

ctest* pTest = NULL;

However, class objects created in the normal way have been allocated memory space at the beginning of creation. The class pointer, if not initialized by the object, does not require a delete release.

The difference between using new and creating an object without using new in C + +

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.