Boost logo

Boost Users :

Subject: Re: [Boost-users] Boost.Signals2 - if slot (functor of lambda) destructs the signal, calling the slot itself -> safe for functor?
From: nice sw123 (nicesw123_at_[hidden])
Date: 2015-09-04 17:45:41


Just to show an example (not using Signals2), where we can
self-destruct a Functor:

This is unsafe (disaster) code.

///////////////////////////////////////////////////////////////////
#include <iostream>
#include <map>
#include <functional>
#include <algorithm>

using namespace std;

using FuncSig = void();
using Func = function<FuncSig>;

class Functor {
public:
  Functor(map<const string, Func> *m_, const string &key_) : m{m_},
key{key_} { cout << "Functor() " << key << endl; }
  Functor(const Functor &other) : m{other.m}, key{other.key} { cout <<
"Functor(const Functor &other) " << key << endl; }
  ~Functor() { cout << "~Functor() " << key << endl; }

  void operator()() const {
    cout << " this == " << this << endl;
    cout << " key == " << key << endl;

    auto it = m->find(key);
    if (it != m->cend()) {
      m->erase(it); // self-destruct
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    }

    cout << " still running code from class (if constructor has
already run, we're in deep trouble... accessing destructed data...)"
<< endl;;
    cout << " this == " << this << endl;
    cout << " key == " << key << endl;
  }

private:
  map<const string, Func> *m;
  const string key;
};

int main()
{
  map<const string, Func> m;
  auto x = m.emplace("hello", Functor(&m, "hello"));
  x.first->second();
  return 0;
}
///////////////////////////////////////////////////////////////////


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net