"C + +" smart pointer in detail (a): The introduction of smart pointers

Source: Internet
Author: User

Smart pointers are a way of using the RAII mechanism (explained later) in C + + to manage pointers through objects.

In C + +, dynamic memory needs to be maintained by ourselves, we must release it manually before the function scope or program exits abnormally , otherwise it will cause a memory leak.

For example: When we use pointer variables to create an object, we need to manually delete it

String * pstr = new string ("Hello world!"); .... delete Pstr;

In fact, even though we are very cautious, there are times when things can still make us impossible:

Case one: Within a branch of the program, forget to free memory void FunTest1 () {int *parr = new INT[10]; file* pFile = fopen ("Test.txt", "R"), if (pfile==null) {return;} ...//Handling other code//.....if (parr!=null) {delete[] Parr;parr = NULL;}}
Scenario Two: When the program throws an exception, forget to release memory void FunTest2 () {int *parr = new int[10];try{//...//other code//...} catch (...) {return;} if (parr!=null) {delete[] Parr;parr = NULL;}}

Each time the dynamic development of memory, you have to manually release, a bit inattentive, will cause a memory leak. (Code a lot, logic a complex, scared I dare not to dynamically open up memory!)

Then, I naturally foolishly expected: if there is something to manage the pointer, let it in the function scope or before the end of the automatic release of memory, it is not flattered?

Therefore, we introduce RAII (resource acquisition is initialization) mechanism: through the class to encapsulate pointers, in the constructor to complete the initialization of resources, in the destructor to complete the cleanup of resources and Shanwei work.

Want to know how to funeral, and listen to tell: Smart pointer detailed auto_ptr

"C + +" smart pointer in detail (a): The introduction of smart pointers

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.