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,
That's probably one of their rare valid use cases, since states should be stateless themselves (which doesn't mean they don't need an instance), and accessible concurrently regardless of the current state machine's context.
So that means you actually just need one instance of a state at a time.
The example shown at the mentioned website, also gives you an unnecessary performance hit, at the cost coming from
new
anddelete
whenever state changes, which could be avoided to have steadystatic
instances for the states.Actually you could consider to provide state instances as with the Flyweight Design Pattern, which essentially boils down to have Singleton state instances.
But well, it depends. UML state diagrams actually allow to have non-stateless states (as composite states with history attributes, or active states).
Have a look at my STTCL template library concept document, it explains some of the aspects, and design decisions I have used, to develop that template library, and how it can be used properly.
Be assured you I don't have any single
delete this;
in there ;-).I'd say that example the website currently gives, is really badly designed and not generally recommendable1.
Using
delete this
isn't appropriate, dangerous and not acceptable, as you mentioned.While using Singleton's is, if you have their valid use case at hand.
1) Sadly enough to notice this, since I've been using it as a "reference" for many design-patterns related questions here.