Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does C++ use std::weak_ptr to break the cycle caused by share_ptrs

Shulou Source: shulou.com Published: 2022-06-01 19:25:55 09月14日 Update

This article introduces the knowledge of "how C++ uses std::weak_ptr to break the cycle caused by share_ptrs". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

R.24: use std::weak_ptr to break the cycle caused by share_ptrs

Reason (reason)

Shared_ptr relies on counting actions, and loop constructs (such as holding shared_ptr each other) can cause counts to never return to zero, so we need a mechanism to break this cycle.

Example (sample)

# include

Class bar

Class foo

{

Public:

Explicit foo (const std::shared_ptr& forward_reference)

: forward_reference_ (forward_reference)

{}

Private:

Std::shared_ptr forward_reference_

}

Class bar

{

Public:

Explicit bar (const std::weak_ptr& back_reference)

: back_reference_ (back_reference)

{}

Void do_something ()

{

If (auto shared_back_reference = back_reference_.lock ()) {

/ / Use * shared_back_reference

}

}

Private:

Std::weak_ptr back_reference_

}

Enforcement (implementation recommendations)

It's almost impossible. If you can statically check for loops, we won't need weak_ptr.

That's all for the content of "how C++ uses std::weak_ptr to break the cycle caused by share_ptrs". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Circulation Clearing content more knowledge practicality achievement almost next actions causes dilemmas reality suggestions situations articles mechanisms cases examples editing Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Docker Shulou Information Redmi OPPO Reno