lundi 3 août 2020

c++ Observer design pattern with smart pointers

recently i started learning design patterns. I tried to use Observer pattern in my project that i'm currently working on. The problem (or maybe not) is that I wrote that on smart pointers (what i thought was great idea). But after i done i've got an error during un-registering object from observer list. After a little of thinking I've realized that when counter of shared_ptr (which I used) will be equal to zero than object pointed by that shared_ptr will be destroyed. Is it correct? Or Am i'm missing something? And if what i'm talking about is true, than of course detachment method which i wrote to un-register that object from observer list will be also uncorrect isn't it?

void detach(std::shared_ptr<ObserverInterface> observer) 
{ 
    auto iterator = std::find(listObserver.begin(), listObserver.end(), observer);
    if(iterator != listObserver.end())  listObserver.erase(iterator);
}

Also after some research I found similar question asked here: "Observer-Pattern" in C++ using Smart Pointer ?

Top answer in that question (about smart pointers in Observer design pattern) was that the whole idea of using here something more than raw pointers is uncorrect. Or if I misunderstood that : " The observer pattern is a typical example of a case where smart pointers (at least the usual candidates) are inappropriate. (...)" But i found his explanation not enaugh for me. So can someone answer me with more details why is (if it is) using here smart pointers a bad idea?

Aucun commentaire:

Enregistrer un commentaire