Click here to Skip to main content
15,880,725 members
Articles / Programming Languages / C++

RAII, Dynamic Objects, and Factories in C++

Rate me:
Please Sign up or sign in to vote.
4.71/5 (38 votes)
3 May 200511 min read 385.3K   777   72  
RAII: automatic resource management in C++.
#ifndef MY_CLASS_H
#define MY_CLASS_H

/**
 * This example code is a supplement to the article 
 * 'RAII, Dynamic Objects, and Factories in C++'
 * at CodeProject: http://www.codeproject.com/
 */

#include "raiifactoryimp.h"


/**
 *  A simple test class
 */
class MyClass {
public:
   MyClass()       : mi(0), md (0.0)         {}
   MyClass (int i) : mi(i), md (0.0)         {}
   MyClass (double d)        : mi(0), md (d) {}
   MyClass (const char* s)   : mi(0), md (0.0) {}
   MyClass (int i, double d) : mi(i), md (d) {}

//#if defined (_MSC_VER) && _MSC_VER <= 1200  // MSVC++ 6.0 may require a destructor here even though it is not necessary
   ~MyClass() {}
//#endif

   void set (int i) { mi = i; }
   int  get () { return mi; }

private:
   int    mi;
   double md;
   
   // non-copyable
  MyClass (const MyClass&);
  MyClass& operator= (const MyClass&);
};


/**
 * RAII Factory for MyClass objects
 */
class MyClassFactory {
public:
   // create
   MyClass* create() { return imp.keep (new MyClass);  }
   MyClass* create (int arg)    { return imp.keep (new MyClass (arg)); }
   MyClass* create (double arg) { return imp.keep (new MyClass (arg)); }
   MyClass* create (const char* s) { return imp.keep (new MyClass (s)); }
   MyClass* create (int arg1, double arg2) { return imp.keep (new MyClass (arg1, arg2)); }

   // additional functions
   MyClass*       operator[] (size_t n) { return imp[n]; }
   const MyClass* operator[] (size_t n) const { return imp[n]; }
   size_t size() { return imp.size(); }
   void dispose (const MyClass* p) { imp.dispose (p); }
private:
   RaiiFactoryImp<MyClass> imp;
};


#endif

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Austria Austria
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions