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 261 — #299<br />
✐<br />
9.3. Stash y Stack con inlines<br />
9.3. Stash y Stack con inlines<br />
Disponi<strong>en</strong>do de inlines, podemos modificar las clases Stash y Stack para hacerlas<br />
más efici<strong>en</strong>tes.<br />
//: C09:Stash4.h<br />
// Inline functions<br />
#ifndef STASH4_H<br />
#define STASH4_H<br />
#include "../require.h"<br />
class Stash {<br />
int size; // Size of each space<br />
int quantity; // Number of storage spaces<br />
int next; // Next empty space<br />
// Dynamically allocated array of bytes:<br />
unsigned char* storage;<br />
void inflate(int increase);<br />
public:<br />
Stash(int sz) : size(sz), quantity(0),<br />
next(0), storage(0) {}<br />
Stash(int sz, int initQuantity) : size(sz),<br />
quantity(0), next(0), storage(0) {<br />
inflate(initQuantity);<br />
}<br />
Stash::~Stash() {<br />
if(storage != 0)<br />
delete []storage;<br />
}<br />
int add(void* elem<strong>en</strong>t);<br />
void* fetch(int index) const {<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 count() const { return next; }<br />
};<br />
#<strong>en</strong>dif // STASH4_H ///:~<br />
Obviam<strong>en</strong>te las funciones pequeñas funcionan bi<strong>en</strong> como inlines, pero note que<br />
las dos funciones más largas sigu<strong>en</strong> si<strong>en</strong>do no-inline, dado que convertirlas a inline<br />
no repres<strong>en</strong>taría ninguna mejora de r<strong>en</strong>dimi<strong>en</strong>to.<br />
//: C09:Stash4.cpp {O}<br />
#include "Stash4.h"<br />
#include <br />
#include <br />
using namespace std;<br />
const int increm<strong>en</strong>t = 100;<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 />
261<br />
✐<br />
✐<br />
✐<br />
✐