c++ - Retrieve object instance from map -


i'm new c++ , i'm trying make little game. have class named "unitcontroller" stores multiple instances of class "unit" in map. class has method "getunit" should return 1 of stored units.

it seems method partially working. think copy of unit instead of requested instance.

could point me int right direction?

#include "unitcontroller.h" #include "unit.h"  using namespace ci; using std::map;  unitcontroller::unitcontroller() { }  void unitcontroller::addunit( vec2f position ) {     unit munit = unit();     munit.setup( position );     units.insert( std::pair<int,unit>( units.size()+1, munit ) ); }  unit unitcontroller::getunit( int k ) {     unit selectedunit = units[0];     return selectedunit; }  void unitcontroller::update() {     for( map<int,unit>::iterator u = units.begin(); u != units.end(); ++u ){         u->second.update();     } }  void unitcontroller::draw() {     for( map<int,unit>::iterator u = units.begin(); u != units.end(); ++u ){         u->second.draw();     } } 

the method:

unit unitcontroller::getunit( int k ) {     unit selectedunit = units[0];     return selectedunit; } 

is returning a, possibly default, copy of element index 0 (do mean ignore k?). if wish avoid copy being returned return reference instead element @ index 0, not local variable selectedunit:

unit& unitcontroller::getunit( int k ) {     return units[k]; } 

if entry keyed k removed map caller has reference unit of entry has dangling reference, use of undefined behaviour. there few things consider try , avoid this:

  1. does client of unitcontroller require direct access unit in map? if not , client requires update attributes of unit modify unitcontroller interface support updates unit without providing client direct access.
  2. if client require direct access consider using std::shared_ptr<unit> instead of unit entry value type (and don't return reference in case). address dangling reference problem mean caller have access unit no longer in unitcontroller?

operator[] create entry in map key not exist:

inserts new element container using key key , default constructed mapped value , returns reference newly constructed mapped value. if element key key exists, no insertion performed , reference mapped value returned.

if wish not have behaviour use find() , decide on action take if entry key k not exist.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -