I've decided to start learning C++ lately; coming from scripting background (Ruby, JavaScript, PHP). I've started building a very simple observer. What I am trying to achieve, is a custom callback for notify method as shown below:
#include <iostream>
#include <functional>
using namespace std;
template<class StateT>
class Observer{
typedef function<void(StateT)> LambdaT;
LambdaT callback;
~Observer(){
//delete callback;
};
public:
void setCallback(LambdaT &callback)
{
this->callback = callback;
};
void notify(StateT state){
this->callback(state);
};
};
int main(int argc, char** argv) {
Observer<string>* obs = new Observer<string>;
std::function<void(string)> customCallback = [](string state){
cout << state << endl;
};
obs->setCallback(customCallback);
obs->notify("State has changed");
return 0;
}
Then I have a Subject to observe, and when Subject instance is being destroyed, all of it's attached observers are being destroyed too, in order to free memory. This was just an idea, which could be wrong in terms of "ideal" implementation, also not sure if that's how I am supposed to clean memory, I haven't tried smart pointers yet.
~Subject(){
for(listIterator......){
delete (*it); //observer instances pointers are stored in a list
}
};
I was planning to pass callback for my observer, as a pointer to setCallback() function, so i can delete it as I delete observer instances from subject. Now my main question is how do I de-allocate memory, which has been occupied by my callback (which is now an observer property)?
Observer<string>* obs = new Observer<string>;unnecessary. Just useObserver<string> obs;- Neil Kirk