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.