My state machine handles requests and returns the next state. In the below simplification, I've got two states here, CreatedState and RunningState. Running state is the end state, and just returns itself. Running state has state (as in memebers) that need to be preseved, I'll use the integer count to represent them.
std::unique_pointer<StateBase> handle();
// Caller
void Call(){
_currentState = _currentState->handle();
}
// Created State Implementation
std::unique_pointer<StateBase> CreatedState::handle(){
return std::make_unique<RunningState>();
}
// Running State Implementation (option 1: create a new one)
std::unique_pointer<StateBase> RunningState::handle(){
return std::make_unique<RunningState>(RunningState(int count));
}
The problem here is that creating a new RunningState with a memento/all-of-the-private-members of the old RunningState is messy and probably inefficient(?).
In a managed language I might just return this, but if I did something like that: return std::make_unique<RunningState>(&this) I would have two pointers to the same object and the destruction of the lhs _currentState in the Call() would leave me with nothing to point at.
How can I cleanly and efficiently leave _currentState unchanged?
std::enable_shared_from_thisbase class was originally designed to solve problems similar to this. However, I have yet to see practical use of it, so I can't comment on its efficacy.std::make_unique<...>(this)does not merely point to the same object. It forwards the arguments to the constructor of the class, effectively copy-constructing another instance, taking your argument instance as the source of data. If you do not define any constructors for your class, C++ will implicitly define one for you.