// MT3Q1.cpp #include #include #include std::string convert(size_t i) { std::ostringstream temp; temp << i; return temp.str(); } typedef std::string Message; class MessagePool { public: // create empty pool MessagePool(size_t poolSize) : numCreated(0), MAX(poolSize) {} size_t size() const { return pool_.size(); } // retrieve message Message* getMessage() { // if pool is empty if(pool_.size() == 0) { // if have not reached MAX messages if(numCreated < MAX) { // create message and return it ++numCreated; std::string temp = std::string("message #") + convert(numCreated); return new Message(temp); } else // otherwise return failure as null message return 0; } else { // otherwise get message from pool and return it Message* pMsg = pool_.back(); pool_.pop_back(); return pMsg; } return 0; } void releaseMessage(Message* pMsg) { // if pool not full if(pool_.size() < MAX && pMsg != 0) // return message to pool pool_.push_back(pMsg); } private: std::vector< Message* > pool_; size_t MAX; size_t numCreated; }; void main() { MessagePool mp(5); Message* MessagePointerArray[7]; for(int i=0; i<7; ++i) { Message* pObj = mp.getMessage(); MessagePointerArray[i] = pObj; if(pObj) std::cout << "\n " << *pObj ; else std::cout << "\n " << "null message"; } std::cout << "\n pool size is " << mp.size(); for(size_t i=0; i<3; ++i) { std::cout << "\n -- releasing message: " << *MessagePointerArray[i]; mp.releaseMessage(MessagePointerArray[i]); } size_t count = mp.size(); std::cout << "\n pool size is " << count; for(size_t i=0; ic_str(); std::cout << "\n\n"; }