I am using the example below to implement a state design pattern.
https://sourcemaking.com/design_patterns/state/cpp/1
I don't wanna delete the *this pointer inside a member class because is not safe (I will call other member function after delete).
class ON: public State
{
  public:
    ON()
    {
        cout << "   ON-ctor ";
    };
    ~ON()
    {
        cout << "   dtor-ON\n";
    };
    void off(Machine *m);
};
class OFF: public State
{
  public:
    OFF()
    {
        cout << "   OFF-ctor ";
    };
    ~OFF()
    {
        cout << "   dtor-OFF\n";
    };
    void on(Machine *m)
    {
        cout << "   going from OFF to ON";
        m->setCurrent(new ON());
        delete this; // <<< This line looks suspect and unsafe
    }
};
void ON::off(Machine *m)
{
  cout << "   going from ON to OFF";
  m->setCurrent(new OFF());
  delete this; // <<< This line looks suspect and unsafe
}
Is there a better approach to implement the state design pattern? I thought about use Singletons, but I want avoid using singletons.
Best regards,
 
     
     
    