Posts

Showing posts from April, 2011

RAII in C++

Spanish version / Versión en Español RAII is an acronym which means "Resource Acquisition Is Initialization". And what's it about? It'a low level design pattern, what some call "idiom". Its aim is to ease and ensure resource deallocation. Resources include file handles, bitmaps, data base connections, heap memory, etc. RAII was created by Bjarne Stroustrup, the face of the team which created C++. Even though RAII was born in C++, it's so general that it can be used in any object oriented language with an exception handling mechanism. It can even be implemented in languages which do not meet these requirements, but it is not so trivial and might not be worth the hassle. The idea is quite simple: allocate the resource ONLY in the constructor and deallocate it ONLY in the destructor. Hence the name RAII: When we initialize the object (call the constructor), we acquire the resource. Initialization is acquisition. Acquisition is Initialization. T

RAII en C++

Versión en inglés / English version RAII es un acrónimo que significa "Resource Acquisition Is Initialization". ¿Y de qué se trata? Es un patrón de diseño de bajo nivel, lo que algunos teóricos llaman "idiom". El problema que busca resolver es facilitar y asegurar la liberación de recursos (archivos, bitmaps, conexiones a base de datos, memoria del heap, etc). La creación de RAII corresponde a Bjarne Stroustrup, líder del equipo creador de C++. Pese a haber nacido en ese lenguaje, RAII es tan general que puede usarse fácilmente en cualquier lenguaje orientado a objetos con manejo de excepciones. Incluso puede implementarse en otros lenguajes, pero no es tan trivial y por ende puede no valer la pena. La idea es muy simple: adquirir el recurso SÓLO en el constructor y liberarlo SÓLO en el destructor. De ahí el nombre RAII: al inicializar (construir) el objeto, adquirimos el recurso. Esto ata el uso del recurso a la vida del objeto, y nos evita andar pensa