I'm creating a game, and trying to learn move semantics/r-value references.
I have a class that adds an Event
into a vector
every frame.
After 60 frames, I want to move all the accumulated events into a new class (called Step
), which will be stored in another vector
.
I want this process to repeat, so after the Event
vector is moved, it should reset to being empty.
#include <vector>
class Event
{
...
}
class Step
{
std::vector<Event> Events;
Step(std::vector<Event>&& InEvents) : Events {InEvents} {}
}
class EventAccumulator
{
std::vector<Event> Events;
std::vector<Step> Steps;
void Update(int FrameCount)
{
Events.push_back(Event());
if (FrameCount % 60 == 0)
{
// Move accumulated events into a new Step.
Step NewStep = Step(std::move(Events));
Steps.push_back(NewStep);
// Reset Events so that we can accumulate future events.
Events = std::vector<Event>();
}
}
}
// Game Loop
int GlobalFrameCount = 0;
EventAccumulator eventAccumulator{};
while (true)
{
eventAccumulator.Update(GlobalFrameCount++);
}
It's my understanding that the line Step NewStep = Step(std::move(Events));
will 'give' Events
to NewStep
(i.e. the vector is not copied). Please correct me if I'm wrong on this.
I want the line Events = std::vector();
to cause EventAccumulator.Events
to be reset to an empty vector, but I do NOT want NewStep.Events
to be reset.
My question is, will this code do what I want?
Additionally, how can you tell whether this will work/not work for all complex classes like std::vector
? I think it's determined by the assignment operator overload of the class, but I'm confused on this.