Recently I learned C ++ 11 and saw the powerful shared_ptr. I thought, why do we still need weak_ptr and weak_ptr for shared_ptr? After exploration, we can see that shared_ptr is also based on reference counting. The problem with reference counting is that during cyclic reference, it may not be able to analyze the structure because the Count value cannot be reduced to 0. The example is as follows:
View code
# Include " Stdafx. h " Using Namespace STD; Struct Linker {shared_ptr <Linker> Link ;}; Void Dowork () {shared_ptr <Linker> L1 (New Linker (); shared_ptr <Linker> L2 ( New Linker (); L1 -> Link = L2; L2 -> Link = L1 ;} Int _ Tmain ( Int Argc, _ tchar * Argv []) {dowork (); _ crtdumpmemoryleaks (); Return 0 ;}
The output window is as follows:
View code
Detected memory leaks! Dumping objects-> {196} normal block at 0x0060dd30, 16Bytes long. Data: <'> A4 D906 00 01 00 00 01 00 00 00 00 E8 DC 60 00{195} normal block at 0x0060dce8, 8Bytes long. Data: <p ''>50 DC 60 00 98 DC 60 00{194} normal block at 0x0060dc98, 16Bytes long. Data: <p '> A4 D906 00 01 00 00 01 00 00 00 50 DC 60 00{193} normal block at 0x0060dc50, 8Bytes long. Data: <'0'> E8 DC 60 00 30 DD 60 00Object dump complete.
This indicates Memory leakage. The solution is simple. You only need to change the link Member type in linker from shared_ptr to weak_ptr so that the pointer does not introduce the count:
View code
# Include " Stdafx. h " Using Namespace STD; Struct Linker {weak_ptr <Linker> Link ;}; Void Dowork () {shared_ptr <Linker> L1 ( New Linker (); shared_ptr <Linker> L2 (New Linker (); L1 -> Link = L2; L2 -> Link = L1 ;} Int _ Tmain ( Int Argc, _ tchar * Argv []) {dowork (); _ crtdumpmemoryleaks (); Return 0 ;}
Now the output window is calm and there is nothing, indicating that there is no memory leakage!