Click here to Skip to main content
15,892,674 members
Articles / Programming Languages / Visual C++ 10.0

SmartObject Class (Objective-C like Memory Management) for C++ (A substitute for Smart Pointer maybe?)

Rate me:
Please Sign up or sign in to vote.
4.55/5 (8 votes)
22 Aug 2013MIT9 min read 35.1K   350   25  
This article explains Objective-C like C++ memory management class, SmartObject.
#include <Windows.h>
#include <tchar.h>
#include <stdio.h>
#include "SmartObject.h"

class TestClass: public SmartObject
{ 
public:
	TestClass():  SmartObject()
	{
		//Initialization 
		m_myVal=new int();
		*m_myVal=1; 
	} 
	
	TestClass  (const TestClass& b): SmartObject(b)

	{
		//Initialization by copying
		m_myVal = new int();
		*m_myVal = *(b.m_myVal); 
	} 
	TestClass & operator=(const TestClass& b)
	{
		if(this!=&b)
		{  
			*m_myVal=*(b.m_myVal);
			SmartObject::operator=(b); 
		}  
		return *this;   
	}
	virtual ~TestClass()
	{
		if(m_myVal)  
			delete m_myVal;  
	}  
	void DoSomething() 
	{ 
		*m_myVal=*m_myVal+1; 
	}  
private: 
	int *m_myVal;  
};   


void SomeFunc(TestClass *sClass)
{
	sClass->RetainObj();
	sClass->DoSomething();
	sClass->ReleaseObj();
}

int _tmain(int argc, _TCHAR **argv)
{
	_tprintf(_T("Example"));

	TestClass testClass;
	testClass.DoSomething();


	TestClass *testClass2 = new TestClass();
	testClass2->RetainObj();
	testClass2->RetainObj();
	SomeFunc(testClass2);
	testClass2->ReleaseObj();
	testClass2->ReleaseObj();
	delete testClass2;






	while(1){}
	return 0;
}

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, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer
United States United States
Woong Gyu La had been working as a software developer for over 8 years.
His personal interests are improving his personal projects,

EpLibrary (Visual C++ Utility Library)
https://github.com/juhgiyo/EpLibrary[^]

EpOraLibrary (Oracle OCI Wrapper Library for Visual C++)
https://github.com/juhgiyo/EpOraLibrary[^]

EpServerEngine (Visual C++ WinSock Server/Client Engine)
https://github.com/juhgiyo/EpServerEngine[^]

And other projects can be found at
https://github.com/juhgiyo?tab=repositories[^]

Finally, my other articles can be found at
http://www.codeproject.com/Articles/juhgiyo#articles[^]

You can contact me at juhgiyo@gmail.com[^]

Comments and Discussions