It is currently Wed Aug 23, 2017 6:51 am

All times are UTC - 5 hours




 Page 1 of 1 [ 2 posts ] 
Author Message
 Post subject: C++ VMK 20 - Unique Pointers
PostPosted: Sat Oct 08, 2011 8:48 am 
Site Admin

Joined: Sun Feb 11, 2007 8:59 am
Posts: 1105
Location: Ontario Canada
Unique pointers are very handy in VC++ 2010. They let you manage your dynamic memory in a smart way making sure they the memory is deallocated when your pointers go out of scope.


Offline
 Profile  
 
 Post subject: Re: C++ VMK 20 - Unique Pointers
PostPosted: Mon Oct 17, 2011 1:03 pm 

Joined: Sat Aug 16, 2008 7:58 am
Posts: 448
I was working around with the unique pointers. I wrote a really nice macro to even simplify the code more. But to use this macro you have to atleast include <memory> and the class object you want to use. This is my own code brand new today, just finished getting it to work correctly and with this setup once you have your variable name you can use both access notations; -> notation to access your class variables and/or functions, and the . notation to access the properties of the unique ptr.

here is the macro in action.
// This would be in either core.h or stdafx.h
#ifndef MYFILE_H
#define MYFILE_H

#ifndef __SMARTPTR__ // CN = ClassName | PCN = POINTERCLASSNAME
   #define CN = class CN;
   #define   upCN = class CN*;
   #define __SMARTPTR__(CN, upCN ) std::unique_ptr<CN> upCN( new CN );
#endif 

#endif // MYFILE_H

// ======================================
// main.cpp
#include "myfile.h"

// Simple class to illustrate use.
class myClass {
private:
   int _iMyVar;
public:
   myClass(){}
   ~myClass(){}

   void setVar( int iVar ) { _iMyVar = iVar; }
   int  getVar() { return _iMyVar; }

};

// Main function - Program startup
int _tmain( int argc, _TCHAR* argv[] ) {

   std::unique_ptr<myClass> upC1( new myClass );
   upC1->setVar( 3 );
   printf( "================================\n" );
   printf( "Using standard c++ notation\n" );
   printf( "The var is: %d\n\n", upC1->getVar() );

   
   __SMARTPTR__( myClass, upC2 );
   upC2->setVar( 26);
   printf( "================================\n" );
   printf( "Using __SMARTPTR__ macro\n" );
   printf( "The var is: %d\n", upC2->getVar() );

    return 0;
}


If you happen to find any bugs in this macro please let me know, I would also like to hear some of your thoughts about this
nice little tool. Once I get a little more time, I will rewatch the video, and make a second macro to do that same but with file pointers.


Offline
 Profile  
 
Display posts from previous:  Sort by  
 Page 1 of 1 [ 2 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Jump to:  

cron