Wednesday, January 16, 2013

Smart Pointer (works as garbage collection) in c++

//smart (auto) pointer is a new feature of c++11
#include <memory>           //     <-- 0
#include <string>
using namespace std;

typedef auto_ptr<Car> CarPtr;


class Car{
    public:
        void startEngine()

        {
            //...................
        }
       
        void tuneRadioTo()

        {
            //...................
        }
};

void f()
{
  CarPtr p(new Car());         //    <-- 1
  p->startEngine();             //    <-- 2
  p->tuneRadioTo();            //    <-- 3
}                                    //    <-- 4

int main()
{
   f();
}
 

0: This gets the definition for auto_ptr
1: Create an object
2: Call a member function
3: Call another member function
4: Destroy the Car object

-----------------------------------------------------------------------------------------------

//Program to show drawback of auto pointer
#include <memory>             
#include <iostream>
using namespace std;

class Test{
    public:
        void print(){
            cout << "Test::print" << endl;
        }
};

int main(){
    auto_ptr<Test>  aptr1(new Test);
    aptr1 -> print();
   
    cout << aptr1.get();
   
    auto_ptr<Test>  aptr2(aptr1);
    aptr2 -> print();
   
    cout << aptr1.get();
    cout << aptr2.get();
   
    return 0;

}

OUTPUT:

To overcome this c++11 provide another mechanism called smart (shared) pointer.

No comments:

Post a Comment