Download Latest Version SimpleRAII_1_00b_Visual_Studio.zip (7.1 kB)
Email in envelope

Get an email when there's a new version of SimpleRAII

Home
Name Modified Size InfoDownloads / Week
VS 2016-04-14
readme.txt 2016-04-14 2.5 kB
SimpleRAII.hxx 2016-04-14 3.2 kB
Totals: 3 Items   5.7 kB 0
SimpleRAII v1.0 Copyright (C) 2016, Andreas Besting.

SimpleRAII is a tiny garbage collection helper class that eases the use of the RAII idiom (Resource 
Acquisition Is Initialization).
Furthermore, it allows the sharing of resources behind the boundaries of class
instances by using reference counting.

Usage: Just include the "SimpleRAII.hxx" file.
When creating a new class, simply subclass the "SimpleRAII" class and 
encapsulate all suitable "new ..." statements with "manage(new ...)". Do not use any delete statements!
As a result, the new class receives ownership of all such embedded objects. The existence of these objects
is bound to the lifespan of their parent object.
That means, all instances will be deleted when the destructor of the parent object is called.

For an example of shared usage and a test program, see "SimpleRAIITest.cpp".

SimpleRAII is released under the BSD LICENSE (see source code header).

3 min. Tutorial:

In short the RAII idiom states that it's a good thing when dealing with resource allocation and 
deallocation in constructors and destructors. In the latter case, code that frees memory is always
guaranteed to be executed, when the object is deleted from the stack.
So, suppose you write a class MyClass that looks like this:

class MyClass {
public:
	MyClass(void){
		s = new std::string();	
	}

	~MyClass(void){
		delete s;
	}

private:
	std::string* s;
}

Here the pointer variable s is initialized as a string objected on the heap which will deleted when 
the instance of MyClass runs out of scope.
To safe yourself some writing whenever you want to do just that, you can use the SimpleRAII helper 
class to achieve that same thing. MyClass would then look like this:

class MyClass : public SimpleRAII {
public:
	MyClass(void){
		s = manage(new std::string());
	}

private:
	std::string* s;
}

Alternative usage:

class MyClass {
public:
	MyClass(void){
		s = raii.manage(new std::string());
	}

private:
    SimpleRAII raii;
	std::string* s;
}

Here, no destructor is needed anymore. Of course you can add a destructor implementation, but you 
don't have to explicitly take care of the deallocation yourself. What happens is that the pointer
of s is stored in a map inside of the base class. Objects in that map are handled in the base class
desctructor. You are allowed to call to manage function not only in the constructor, but anywhere else.
Source: readme.txt, updated 2016-04-14