Here's the code. The question follows.
Ok, first off. The SAFE_DELETE is defined then undefined, because most of my classes need a different version of it.Code:#pragma once #define SAFE_DELETE(var) if ( var ) { delete var; var = 0; } template<class T> class Type { public: //Default constructor Type() :is_good(false), typePtr(0) {/*Empty code block*/}; //Assignment constructor Type(const T& val) :is_good(false), typePtr(0) { //Allocate memory with assigned value typePtr = new T(val); if ( *typePtr == val ) is_good = bool(true); else { SAFE_DELETE(typePtr); } }; //Copy constructor //Does not copy pointers. Copies values. Type(const Type& copy) :is_good(false), typePtr(0) { //Allocate memory with copy values typePtr = new T(*copy.typePtr); if ( *typePtr == *copy.typePtr ) is_good = bool(true); else { SAFE_DELETE(typePtr); } }; //Destructor ~Type() { is_good = false; SAFE_DELETE(typePtr); }; //Copy assignment const Type& operator=(const Type& copy) { if ( typePtr ) { is_good = bool(false); SAFE_DELETE(typePtr); } typePtr = new T(*copy.typePtr); is_good = copy.is_good; return *this; }; T& operator*() { return *typePtr; }; T* operator->() { return typePtr; }; operator bool() { return is_good; }; private: bool is_good; //The pointer to the type T* typePtr; }; #undef SAFE_DELETE
The point of the class is to wrap the handling of the pointer. Pretty much to disallow modifying the pointer without ugly code.
My thought on this is that with this class I can do something like the following.
I realize that there isn't much difference between them, but I thought I would see what you guys thought. Well Thank you.Code:Type<int> Test(100); if ( Test )//check if the ptr is good std::cout << *Test << std::endl; //As opposed to int * Test = new int(100); if ( Test != 0 ) std::cout << *Test << std::endl; delete Test;
EDIT:
Also, if I am not mistaken the only way to directly modify the pointer, or to prematurely delete would be to do this right?
Code:Type<int> Test(100); delete Test.operator->();//Am i right?



LinkBack URL
About LinkBacks



CornedBee