maht0rz
maht0rz

Reputation: 96

C++ lambda pointer/reference memory occupation struggle

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)?

Upvotes: 0

Views: 184

Answers (1)

Etienne Maheu
Etienne Maheu

Reputation: 3255

You don't. The callback property is not dynamically allocated. You only need to make sure to deallocate your observer. As a rule of thumb, there should be one delete for each new. Since you never use new for a LambdaT, then there is no need for delete.

Since the setCallback method takes a reference to your callback, this method sees the same value as your main method. But, you do not store a reference to the callback, you store a copy of the callback. So to make this clear:

  • customCallback is the original value.
  • callback is a reference to customCallback.
  • Observer::callback is a copy of callback.

Upvotes: 1

Related Questions