Pensar en C++ (Volumen 1) - Grupo ARCO
Pensar en C++ (Volumen 1) - Grupo ARCO
Pensar en C++ (Volumen 1) - Grupo ARCO
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
✐<br />
✐<br />
✐<br />
“Volum<strong>en</strong>1” — 2012/1/12 — 13:52 — page 493 — #531<br />
✐<br />
16.4. Stack y Stash como Plantillas<br />
template<br />
T* PStash::operator[](int index) const {<br />
require(index >= 0,<br />
"PStash::operator[] index negative");<br />
if(index >= next)<br />
return 0; // To indicate the <strong>en</strong>d<br />
require(storage[index] != 0,<br />
"PStash::operator[] returned null pointer");<br />
// Produce pointer to desired elem<strong>en</strong>t:<br />
return storage[index];<br />
}<br />
template<br />
T* PStash::remove(int index) {<br />
// operator[] performs validity checks:<br />
T* v = operator[](index);<br />
// "Remove" the pointer:<br />
if(v != 0) storage[index] = 0;<br />
return v;<br />
}<br />
template<br />
void PStash::inflate(int increase) {<br />
const int psz = sizeof(T*);<br />
T** st = new T*[quantity + increase];<br />
memset(st, 0, (quantity + increase) * psz);<br />
memcpy(st, storage, quantity * psz);<br />
quantity += increase;<br />
delete []storage; // Old storage<br />
storage = st; // Point to new memory<br />
}<br />
#<strong>en</strong>dif // TPSTASH_H ///:~<br />
El tamaño del increm<strong>en</strong>to por defecto es muy pequeño para garantizar que se<br />
produzca la llamada a inflate(). Esto nos asegura que funcione correctam<strong>en</strong>te.<br />
Para comprobar el control de propiedad de PStack <strong>en</strong> template, la sigui<strong>en</strong>te<br />
clase muestra informes de creación y destrucción de elem<strong>en</strong>tos, y también garantiza<br />
que todos los objetos que hayan sido creados sean destruidos. AutoCounter<br />
permitirá crear objetos <strong>en</strong> la pila sólo a los objetos de su tipo:<br />
//: C16:AutoCounter.h<br />
#ifndef AUTOCOUNTER_H<br />
#define AUTOCOUNTER_H<br />
#include "../require.h"<br />
#include <br />
#include // Standard <strong>C++</strong> Library container<br />
#include <br />
class AutoCounter {<br />
static int count;<br />
int id;<br />
class CleanupCheck {<br />
std::set trace;<br />
public:<br />
void add(AutoCounter* ap) {<br />
trace.insert(ap);<br />
493<br />
✐<br />
✐<br />
✐<br />
✐