Ok what the hell, I hate this freaking code snippet:
1 2 3 4 5 6 7 8 9
template<class NewState, typename... Args>
void changeState(Args &&... args)
{
//make sure we can create the new state first
std::unique_ptr<State> temp {new NewState(std::forward<Args>(args)...)};
//then swap ownership
state.swap(temp);
//temp properly deletes the old state at the end of its scope
}
It's confusing. I have no idea what's going on, other than it can change the state pointer of Application. But I don't understand the point of the variadic templates here at all.
And while asking around, it was brought to my attention that: state.reset (new NewState (std:forward<Args> (args)...));
can accomplish the what this function does, but in one line.
If someone wants to walk through this code, that would be awesome.
the ability to do it in one line doesnt always make it better. and it looks like it is changing a global called state of type State to hold the new args
That code is no different than emplace() provided by some of the standard library containers ?
All it allows you to do is construct an object by passing the arguments of a constructor to the changeState function which then sends those arguments to the constructor. It allows you to use any constructor without having to create a function definition for every possible constructor an object has.
You could just do this, the swap is a bit redundant really.
And while asking around, it was brought to my attention that: state.reset (new NewState (std:forward<Args> (args)...));
can accomplish the what this function does, but in one line.
That's assuming the destructor for the object of state doesn't throw an exception, otherwise i'm pretty sure you'd have a memory leak. Though i doubt any destructors throw an exception.
There wasn't a reason for extra parameters to be used int he example I created. I should probably fix that.
An example where this would be useful would be, say, a credits screen or something that outputs your score from the game. The score variable could be passed from the game state to the credit state via the constructor.
> because a type that inherits AppState doesn't have a guaranteed size of parameters in it's constructor.
¿is it right and just for the `AppState' to be created inside the `changeState()' method?
`disp' is stored as a member in `app' (a reference called `display'), and `app' can be obtained with `this'
You only add noise and make it error prone.