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:
- does client of
unitcontrollerrequire direct accessunitinmap? if not , client requires update attributes ofunitmodifyunitcontrollerinterface support updatesunitwithout providing client direct access. - if client require direct access consider using
std::shared_ptr<unit>instead ofunitentry value type (and don't return reference in case). address dangling reference problem mean caller have accessunitno longer inunitcontroller?
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
Post a Comment