Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report