Shared_ptr and weak_ptr

Source: Internet
Author: User

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!

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.