lundi 24 juin 2019

shared_from_this with an abstract class causing bad_weak_ptr

I am using an abstract class to define an observer, and from class that implements it I want to register it using something like register(this) but with the shared pointer so using shared_from_this() but I am getting bad_weak_ptr.

I understand I that the exceptionr I am getting is because the pointer is empty and I need to create the pointer but not sure how since this is an abstract class I tried to use make shared but no luck yet. Thanks

Abstract-Observer.hpp

class Observer : public std::enable_shared_from_this<Observer>{
public:

virtual void update() = 0;

}

Example.hpp

class Example : public Observer {
public:
Example();
~ Example();

virtual void update() override;
void useTheObserver();
void registerObserver(shared_ptr(Observer));

}

Example.cpp

class Example::Example:{

}

Example:useTheObserver(){

***//Exception of weak_ptr here***
registerObserver(shared_from_this());


}

 Example:registerObserver(){
}

Example::update(){ 
//some code here
}

Aucun commentaire:

Enregistrer un commentaire