mirror of
https://github.com/isocpp/CppCoreGuidelines.git
synced 2024-03-22 13:30:58 +08:00
add example for R.24 (#1127)
* add example for R.24 taken from https://cpppatterns.com/patterns/weak-reference.html, where it's published under CC0 Public Domain Dedication * improve example for R.24
This commit is contained in:
parent
9de66ec027
commit
2bdd1ae705
@ -9151,7 +9151,35 @@ be able to destroy a cyclic structure.
|
||||
|
||||
##### Example
|
||||
|
||||
???
|
||||
#include <memory>
|
||||
|
||||
class bar;
|
||||
|
||||
class foo
|
||||
{
|
||||
public:
|
||||
explicit foo(const std::shared_ptr<bar>& forward_reference)
|
||||
: forward_reference_(forward_reference)
|
||||
{ }
|
||||
private:
|
||||
std::shared_ptr<bar> forward_reference_;
|
||||
};
|
||||
|
||||
class bar
|
||||
{
|
||||
public:
|
||||
explicit bar(const std::weak_ptr<foo>& 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<foo> back_reference_;
|
||||
};
|
||||
|
||||
##### Note
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user