C ++ smart pointer management and smart pointer Management

Source: Internet
Author: User

C ++ smart pointer management and smart pointer Management
1. the programmer explicitly releases the memory

For c ++ programmers, the most important thing is to manage the dynamically allocated memory. C ++ memory allocated on the heap requires the programmer to release the allocated memory. But sometimes the release of memory does not seem very easy, the following program

Void func () {int * p = new int (0); if (some judgments) {return;} p = new int (1); delete p ;}

This function makes no sense, just to illustrate the problem. The func function has at least three problems. 1. Once the if condition is true, the return statement will be executed immediately. At this time, the memory pointed to by p will not be released (this beginner will generally make a mistake ). 2. p = new int (1); the statement does not release the memory originally allocated to the heap. As a result, the original memory will never be released until the end of the program. 3. This problem is not so obvious. Assume that the code of the func () function is very long.

void func(){    int *p = new int(0);    ...    delete p;}

There is a lot of code between int * p = new int (0) and delete p, and the code in the middle may have executed delete p and not set p to 0. P is the suspension pointer. Executing delete p later will cause a running error.

2. A smart pointer management class similar to boost shared_ptr

The following is a smart pointer management class written by c ++ primer and Objective c ++. With SmartPtr, you no longer need to worry about memory release issues.

# Ifndef SMARTPTR_INCLUDE_H # define SMARTPTR_INCLUDE_H # include <iostream> using namespace std; namespace commutil {template <typename T> class SmartPtr {public: SmartPtr (T * p = 0 ); smartPtr (const SmartPtr &); SmartPtr & operator = (const SmartPtr &);~ SmartPtr (); T & operator * (); T * operator-> (); private: void decreaseRef (); T * m_p; int * m_useCnt ;}; template <typename T> SmartPtr <T>: SmartPtr (T * p = 0): m_p (p) {// when you call this constructor, the default reference number is 1 m_useCnt = new int (1);} template <typename T> SmartPtr <T>: SmartPtr (const SmartPtr & rhs) {// use the copy constructor, create a new object, reference shujia 1 this-> m_p = rhs. m_p; this-> m_useCnt = rhs. m_useCnt; (* m_useCnt) ++;} template <typename T> SmartPtr <T> ::~ SmartPtr () {decreaseRef ();} template <typename T> void SmartPtr <T >:: decreaseRef () {if (-- (* m_useCnt) = 0) {// when the number of references is 0, the heap memory is released delete m_useCnt; delete m_p ;}} template <typename T> T & SmartPtr <T >:: operator *() {// return * m_p;} template <typename T> T * SmartPtr <T>: operator-> () {// overload-> operator, returns the actual object pointer return m_p;} template <typename T> SmartPtr <T> & SmartPtr <T>: operator = (const SmartPtr & anoth ErPtr) {if (this = & anotherPtr) {// prevent the return * this;} // use the value assignment operator to reduce the number of references of the originally referred object by 1. DecreaseRef (); m_p = anotherPtr. m_p; m_useCnt = anotherPtr. m_useCnt; ++ * m_useCnt; // points to the new object, and the number of referenced objects plus 1 return * this ;}# endif
3. Use SmartPtr case study 3.1 The first SmartPtr instance
void func(){    SmartPtr<int> autoPtr(new int(1));}

In func, A SmartPtr object autoPtr is defined, and a memory block is allocated on the stack with the new int (1). The first address of the allocated memory is passed to the SmartPtr constructor. In this case, the m_useCnt value of autoPtr is 1. When the func execution is complete, the autoPtr object exceeds its scope and calls the autoPtr destructor. Call the private decreaseRef () function in the destructor. In decreaseRef (), reduce the memory value of m_useCnt in autoPtr by 1. In this case, if m_useCnt refers to 0, delete m_useCnt; delete m_p ;. The dynamically allocated memory is released when an autoPtr object is created.

3.2 SmartPtr with return statement
Void func () {SmartPtr <int> autoPtr (new int (1); if (Judgment condition) {return ;}}

When the if condition in the func () function is set, after the return statement is executed, autoPtr is out of its range and the memory is released. For analysis, see section 3.1.

3.3 SmartPtr Object Management New SmartPtr object
    SmartPtr<int> autoPtr1(new int(0));    SmartPtr<int> autoPtr2(new int(1));    autoPtr1 = autoPtr2;

Execute autoPtr1 = autoPtr2 because the SmartPtr class overload the value assignment operator. The actual execution is the operator = () function of SmartPtr. In the above value assignment statement, the m_useCnt of autoPtr1 indicates that the memory value is reduced by 1. At this time, the memory value m_useCnt indicates is changed to 0, and the memory value m_p indicates is released. SmartPtr is used to solve the second problem mentioned in 1. In addition, all memory management and release work is performed by SmartPtr, so programmers do not need to worry about when to release the memory.

3.4SmartPtr share object Resources

Unlike auto_ptr, SmartPtr uses the reference counting mechanism to ensure that multiple SmartPtr objects can manage the same object resource.

void func(){    SmartPtr<int> autoPtr1(new int(0));    SmartPtr<int> autoPtr2(autoPtr1);}

Run SmartPtr autoPtr2 (autoPtr1) to call the copy constructor of SmartPtr. In the copy constructor, m_useCnt and m_p of autoPtr2 point to the memory pointed to by autoPtr1 respectively, and then add 1 to the reference number of m_useCnt. At the end of the func () function, the SmartPtr destructor is called twice. The reference value of the two destructor is 0, and the memory referred to by m_useCnt and m_p is deleted.

3.5SmartPtr member functions
class A{public:    void print()    {        cout<<"A"<<endl;    }};void func(){    A *obj = new A();    obj->print();    delete obj;}

SmartPtr reloads the-> operator to allow the SmartPtr object to access member functions like a pointer.

void func(){    SmartPtr<A> autoPtr(new A());    autoPtr->print();}
4. Summary

The SmartPtr class implements "self-management" of memory objects. Using SmartPtr, programmers no longer need to worry about the release of dynamic memory. Unlike shared_ptr, The SmartPtr class can only manage pointer-type resources, and SmartPtr does not support Custom Resource release functions.

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.