c++ - how to count not deleted instances in array of instances? -
i have array of instances in code, :
class squad : public isquad { public: squad(void); squad(squad const & src); virtual ~squad(void); int getcount(void) const; int push(ispacemarine*); ispacemarine* getunit(int) const; ispacemarine** getunits(void) const; int getcapacity(void) const; squad & operator=(squad const & rhs); private: ispacemarine **_units; // here array of instances int const _squadcapacity; };
initialized in constructor
squad::squad(void) : _units(new ispacemarine*[64]), _squadcapacity(64) { return; }
first, the way ?
if yes, try count number of valid instances in array (not null
, not deleted
) don't know how check if _units[20]
deleted example.
how can ?
he current way do:
int squad::getcount(void) const { int count = 0; while (this->_units[count] != null && count < this->_squadcapacity) count++; return count; }
ispacemarine **_units; // here array of instances int const _squadcapacity;
- first, the way ?
no, not way go , neatly shows why std containers , smart pointers big improvement.
with smart pointers express , deal ownership automatically.
i impression squad
manages spacemarines
, in case should use std::unique_ptr
. squad
like
class squad : public isquad { public: size_t getcount() const; void push(ispacemarine&&); using spacemarineiterator = std::vector<std::unique_ptr<spacemarine>>::iterator; // typedef/using iterator appropriate. spacemarineiterator getunit(int) const; // , spacemarineiterator begin() const; spacemarineiterator end() const; size_t getcapacity() const; // no need copy assign either. //squad & operator=(squad const & rhs); private: std::vector<std::unique_ptr<ispacemarine>> units; // no need capacity. };
now, if need different model ownership can std::shared_ptr
, std::weak_ptr
. model should make effort work std::unique_ptr
though.
note: don't discard possibility of using
std::vector<spacemarine> units;
Comments
Post a Comment