Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Observer-Pattern" in C++ using Smart Pointer ? [closed]

Professionals out there,

this is the first time that I'm actually posting a question to this board that helped me out a lot in the past. I'm still a programming novice and have been trying to learn a lot about programming & software development in the last few months.

I recently tackled the topic "c++11-Smart Pointers" and decided rewrite all the Design Patterns I learned a few weeks earlier, including the"Observer Pattern" using shared_ptr & weak_ptr for resource management.

When I was trying to write a simple Implementation of the observer pattern (like in Head First's Design Pattern or Design Patterns by E.Gamma), using an interface-class for both the observable subjects and the observers, and exactly one concrete class for each, I received various error messages from Visual Studio. I just don't understand how to combine shared_ptr and weak_ptr in this pattern, which might be due to the fact that I still don't fully understand the the combination of both.

Unfortunatelly, even a thorough search on the Internet didn't provide me with a simple example of an "observer-pattern using smart-pointer" that can serve as a orientation for me.

I therefore was wondering, if one of you guys would know where to find such a simple implmentation or be so kind to provide me with one of your own. Both would be really really helpful :-)

Thanks a lot

coderAndi

like image 898
CoderAndi Avatar asked Mar 20 '26 19:03

CoderAndi


1 Answers

The observer pattern is a typical example of a case where smart pointers (at least the usual candidates) are inappropriate. Neither the subject nor the object "own" one another; each has its own lifespan. In fact, one frequent use of the observer pattern is when an object has a pointer to another object which it doesn't own. It registers as an observer, so as to be informed when the observed object is destructed.

It sounds to me like you're attacking the entire thing backwards. You have a solution (smart pointers), and you're trying to make every problem fit it. That never works.

like image 79
James Kanze Avatar answered Mar 23 '26 07:03

James Kanze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!