C ++ smart pointer loop reference solution

Source: Internet
Author: User

Statement: the introduction of smart pointers in C ++ makes developers take up the peak in the fight against memory. However, nothing is perfect, and the circular reference defect of smart pointers will still lead to memory leakage. This article describes how to solve the memory problems caused by cyclic references.

Background: The smart pointer uses the Boost library, the C ++ language, and the development tool VS2005. The example program is a Win32 program.
Example of loop reference

[Cpp]
# Include "stdafx. h"
# Include <string>
# Include <iostream>
# Include <boost/shared_ptr.hpp>
# Include <boost/weak_ptr.hpp>
 
Using namespace std;
Using namespace boost;
 
Class cpoliceref
{
Public:
~ CCycleRef ()
{
Cout <"destroying CCycleRef" <endl;
}
 
Public:
Shared_ptr <CCycleRef> selfRef;
};
 
Void assumereftest ()
{
Shared_ptr <CCycleRef> partition REF (new CCycleRef ());
Required ref-> selfRef = required ref;
 
Cout <"reference count:" <symbol ref. use_count () <endl;
}
 
Int _ tmain (int argc, _ TCHAR * argv [])
{
Assumereftest ();

Return 0;
}

Running result:
Reference count: 2

The created cassumeref object is not released.
The reason is that the cpoliceref class is self-referenced and the reference count is increased. The class diagram is as follows.

 

Cyclic reference solution

The weak_ptr weak reference pointer can be used to solve the circular reference problem. Weak_ptr does not modify the reference count.
Modify the cpoliceref class.
[Cpp]
Class cpoliceref
{
Public:
~ CCycleRef ()
{
Cout <"destroying CCycleRef" <endl;
}
 
Public:
Weak_ptr <CCycleRef> selfRef;
};

Running result
Reference count: 1
Destroying cpoliceref

The created CCycleRef object has been released.

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.