13.01.2015 Views

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

Pensar en C++ (Volumen 1) - Grupo ARCO

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

✐<br />

✐<br />

✐<br />

“Volum<strong>en</strong>1” — 2012/1/12 — 13:52 — page 385 — #423<br />

✐<br />

13.2. Rediseño de los ejemplos anteriores<br />

se asigna espacio para un vector de punteros a void.<br />

El destructor de la clase libera el espacio <strong>en</strong> el que se almac<strong>en</strong>an los punteros<br />

sin tratar de borrar los objetos a los que hac<strong>en</strong> refer<strong>en</strong>cia, ya que esto, insistimos,<br />

liberaría el espacio asignado a los objetos, pero no se produciría la necesaria llamada<br />

a sus destructores por la falta de información de tipo.<br />

El otro cambio realizado es el reemplazo de la función fetch() por operator<br />

[], más significativo sintácticam<strong>en</strong>te. Su tipo de retorno es nuevam<strong>en</strong>te void*, por<br />

lo que el usuario deberá recordar el tipo de los objetos a que se refier<strong>en</strong> y efectuar<br />

la adecuada conversión al extraerlos del cont<strong>en</strong>edor. Resolveremos este problema <strong>en</strong><br />

capítulos posteriores.<br />

Sigue la definición de los métodos de PStash:<br />

//: C13:PStash.cpp {O}<br />

// Pointer Stash definitions<br />

#include "PStash.h"<br />

#include "../require.h"<br />

#include <br />

#include // ’mem’ functions<br />

using namespace std;<br />

int PStash::add(void* elem<strong>en</strong>t) {<br />

const int inflateSize = 10;<br />

if(next >= quantity)<br />

inflate(inflateSize);<br />

storage[next++] = elem<strong>en</strong>t;<br />

return(next - 1); // Index number<br />

}<br />

// No ownership:<br />

PStash::~PStash() {<br />

for(int i = 0; i < next; i++)<br />

require(storage[i] == 0,<br />

"PStash not cleaned up");<br />

delete []storage;<br />

}<br />

// Operator overloading replacem<strong>en</strong>t for fetch<br />

void* 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 />

// Produce pointer to desired elem<strong>en</strong>t:<br />

return storage[index];<br />

}<br />

void* PStash::remove(int index) {<br />

void* v = operator[](index);<br />

// "Remove" the pointer:<br />

if(v != 0) storage[index] = 0;<br />

return v;<br />

}<br />

void PStash::inflate(int increase) {<br />

const int psz = sizeof(void*);<br />

void** st = new void*[quantity + increase];<br />

385<br />

✐<br />

✐<br />

✐<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!