How does C++ use std::weak_ptr to break the cycle caused by share_ptrs
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!