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

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

arco.esi.uclm.es
from arco.esi.uclm.es More from this publisher
13.01.2015 Views

✐ ✐ ✐ “Volumen1” — 2012/1/12 — 13:52 — page 194 — #232 ✐ Capítulo 6. Inicialización y limpieza }///:~ En el código anterior, tanto el goto como el switch pueden saltar la sentencia en la que se invoca un constructor. Ese objeto corresponde al ámbito incluso si no se invoca el constructor, de modo que el compilador dará un mensaje de error. Esto garantiza de nuevo que un objeto no se puede crear si no se inicializa. Todo el espacio de almacenamiento necesario se asigna en la pila, por supuesto. Ese espacio lo faciliza el compilador moviendo el puntero de pila «hacia abajo» (dependiendo de la máquina implica incrementar o decrementar el valor del puntero de pila). Los objetos también se pueden alojar en el montículo usando new, algo que se verá en el capítulo 13. (FIXME:Ref C13) 6.4. Stash con constructores y destructores Los ejemplos de los capítulos anteriores tienen funciones que tienen correspondencia directa con constructores y destructores: initialize() y cleanup(). Éste es el fichero de cabecera de Stash, utilizando constructor y destructor: //: C06:Stash2.h // With constructors & destructors #ifndef STASH2_H #define STASH2_H class Stash { int size; // Size of each space int quantity; // Number of storage spaces int next; // Next empty space // Dynamically allocated array of bytes: unsigned char* storage; void inflate(int increase); public: Stash(int size); ~Stash(); int add(void* element); void* fetch(int index); int count(); }; #endif // STASH2_H ///:~ Las únicas definiciones de métodos que han cambiado son initialize() y c- leanup(), que han sido reemplazadas con un constructor y un destructor. //: C06:Stash2.cpp {O} // Constructors & destructors #include "Stash2.h" #include "../require.h" #include #include using namespace std; const int increment = 100; Stash::Stash(int sz) { 194 ✐ ✐ ✐ ✐

✐ ✐ ✐ “Volumen1” — 2012/1/12 — 13:52 — page 195 — #233 ✐ 6.4. Stash con constructores y destructores } size = sz; quantity = 0; storage = 0; next = 0; int Stash::add(void* element) { if(next >= quantity) // Enough space left inflate(increment); // Copy element into storage, // starting at next empty space: int startBytes = next * size; unsigned char* e = (unsigned char*)element; for(int i = 0; i < size; i++) storage[startBytes + i] = e[i]; next++; return(next - 1); // Index number } void* Stash::fetch(int index) { require(0 = next) return 0; // To indicate the end // Produce pointer to desired element: return &(storage[index * size]); } int Stash::count() { return next; // Number of elements in CStash } void Stash::inflate(int increase) { require(increase > 0, "Stash::inflate zero or negative increase"); int newQuantity = quantity + increase; int newBytes = newQuantity * size; int oldBytes = quantity * size; unsigned char* b = new unsigned char[newBytes]; for(int i = 0; i < oldBytes; i++) b[i] = storage[i]; // Copy old to new delete [](storage); // Old storage storage = b; // Point to new memory quantity = newQuantity; } Stash::~Stash() { if(storage != 0) { cout

✐<br />

✐<br />

✐<br />

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

✐<br />

6.4. Stash con constructores y destructores<br />

}<br />

size = sz;<br />

quantity = 0;<br />

storage = 0;<br />

next = 0;<br />

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

if(next >= quantity) // Enough space left<br />

inflate(increm<strong>en</strong>t);<br />

// Copy elem<strong>en</strong>t into storage,<br />

// starting at next empty space:<br />

int startBytes = next * size;<br />

unsigned char* e = (unsigned char*)elem<strong>en</strong>t;<br />

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

storage[startBytes + i] = e[i];<br />

next++;<br />

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

}<br />

void* Stash::fetch(int index) {<br />

require(0 = 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 * size]);<br />

}<br />

int Stash::count() {<br />

return next; // Number of elem<strong>en</strong>ts in CStash<br />

}<br />

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

require(increase > 0,<br />

"Stash::inflate zero or negative increase");<br />

int newQuantity = quantity + increase;<br />

int newBytes = newQuantity * size;<br />

int oldBytes = quantity * size;<br />

unsigned char* b = new unsigned char[newBytes];<br />

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

b[i] = storage[i]; // Copy old to new<br />

delete [](storage); // Old storage<br />

storage = b; // Point to new memory<br />

quantity = newQuantity;<br />

}<br />

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

if(storage != 0) {<br />

cout

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

Saved successfully!

Ooh no, something went wrong!