I have a problem with using the inbuilt & references in C++ correctly. I have an instance of a class named "Entity" it was created in the main() function. I also have an instance of a class named "Simulation" the Simulation class has a function named: addEntity(Entity e) I think that passing an instance into this function just creates a copy of it since the Simulation class then uses this instance to change it's data. After the data got changed the instance in the main() keeps it's default values.
Code:
This is the addEntity function:
void Simulation::addEntity(Entity& entity)
{
simulation_entities.push_back(std::reference_wrapper<Entity>{entity});
}
This function uses the Entity instances to call their public functions.
void Simulation::simThread()
{
while(simulation_state == SimulationState::Running)
{
auto start = std::chrono::system_clock::now();
for (int i = 0; i<simulation_entities.size(); i++)
{
Entity e = simulation_entities[i];
e.tick(simulation_entities);
}
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
std::this_thread::sleep_for(simulation_speed - elapsed);
}
}
This is the tick method which changes internal variables of the Entity instance
void Entity::tick(vector<std::reference_wrapper<Entity>> e)
{
std::cout << Entity::x << std::endl;
Entity::x += entity_velocity[0];
x += entity_velocity[0];
y += entity_velocity[1];
z += entity_velocity[2];
std::cout << "after " << Entity::x << std::endl;
}
But when i try to use the instance after it was supposed to be edited by the code above it still retains it's default values...