Vyoms OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Bookmark and Share Rss Feeds

Understanding & Implementing Smart Pointer in C++ | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Sponsored Ads
Hot Jobs
Fresher Jobs
Experienced Jobs
Government Jobs
Walkin Jobs
Placement Section
Company Profiles
Interview Questions
Placement Papers
Resources @ VYOMS
Companies In India
Consultants In India
Colleges In India
Exams In India
Latest Results
Notifications In India
Call Centers In India
Training Institutes In India
Job Communities In India
Courses In India
Jobs by Keyskills
Jobs by Functional Areas
Learn @ VYOMS
GATE Preparation
GRE Preparation
GMAT Preparation
IAS Preparation
SAP Preparation
Testing Preparation
MBA Preparation
News @ VYOMS
Freshers News
Job Articles
Latest News
India News Network
Interview Ebook
Get 30,000+ Interview Questions & Answers in an eBook.
Interview Success Kit - Get Success in Job Interviews
  • 30,000+ Interview Questions
  • Most Questions Answered
  • 5 FREE Bonuses
  • Free Upgrades

VYOMS TOP EMPLOYERS

Wipro Technologies
Tata Consultancy Services
Accenture
IBM
Satyam
Genpact
Cognizant Technologies

Home » Articles » Understanding & Implementing Smart Pointer in C++

Understanding & Implementing Smart Pointer in C++








Article Posted On Date : Thursday, February 9, 2012


Understanding & Implementing Smart Pointer in C++
Advertisements

Now we have new C++ standards with us. The new standards have taken into account some of the real good features which were missing in C++. But this article has nothing to do with C++11. perhaps my future articles will talk about them but this article talks about the smart pointers and contains a rudimentary implementation of "auto_ptr".
Background

One of the major benefits of using C++ is its deterministic nature. Using C++, we can deterministically control our memory allocation and deallocation(new and delete). but sometimes this becomes a problem. If a novice programmer forgets to delete any object created by new, then we have a memory leak. In case of long running systems, even small memory leaks will create bigger problems. So how can we ensure that for every new, there is a corresponding delete.

One way to do so is to use auto_ptr available in C++. auto_ptr transfers the ownership on copy operations but if we need shared ownership then perhaps we can use boost libraries' smart pointers. But to really understand how these things must be working internally, we need to first implement them. Implementing smart pointers gives us the full understanding of why we need smart pointers, how they are working underneath and where to look for if we have some bug. This exercise here is an implementation of auto_ptr. The main idea is to understand how auto_ptr takes care of transfer of ownership and using various other operations.
Using the Code

The project contains two main classes. Our implementation of smart pointer in MyAuto_Ptr and other class to test this smart pointer MyTestObject. The test suite is written in the main class.

I have put in comments in all the places where we need to know what that code is doing so without talking any more, I give you the code.
The Test Class
Collapse | Copy Code

class MyTestObject
{
    string name;
    int age;

public:
    MyTestObject(string s, int a)
    {
        name = s;
        age = a;
        cout << "Object created ";
    }

    ~MyTestObject(void)
    {
        cout << "Object destroyed ";
    }

    string GetName()
    {
        return name;
    }

    int GetAge()
    {
        return age;
    }
};

Our Smart Pointer
Collapse | Copy Code

template <class T>
class MyAuto_Ptr
{
private:
    T *ptr;

public:

    //Constructor
    explicit MyAuto_Ptr(T *p = 0)
        :ptr(p)
    {

    }

    //Desctructor
    ~MyAuto_Ptr(void)
    {
        //check if null or not
        if(0 != ptr)
        {
            delete ptr;
        }
    }

    //Copy constructor
    MyAuto_Ptr(MyAuto_Ptr<T> &source)
    {
        ptr = source.ptr;

        //Since the ownership gets transferred lets point the source to 0
        source.ptr = 0;
    }

    MyAuto_Ptr& operator=(MyAuto_Ptr<T> &source)
    {
        //check for self reference
        if(ptr != source.ptr)
        {
            //flush the existing memory
            if(0 != ptr)
            {
                delete ptr;
            }

            // use the new pointer
            ptr = source.ptr;

            //Since the ownership gets transferred lets point the source to 0
            source.ptr = 0;

            return *this;
        }
    }

    //Access the value of pointer
    T& operator *()
    {
        return *ptr;
    }

    //Access the pointer
    T* operator ->()
    {
        return ptr;
    }

    //Get the value of pointer
    T* get()
    {
        return ptr;
    }

    //reset the value of pointer
    void reset(T *newVal)
    {
        if(0 != ptr)
        {
            delete ptr;
            ptr = newVal;
        }
    }

    //release the pointer and returns the ownership
    T* release()
    {
        if(0 != ptr)
        {
            T *t = ptr;
            ptr = 0;
            return t;
        }
    }
};

Testing the Class (Main)
Collapse | Copy Code

int main(int argc, char* argv[])
{
    {//dummy brace to test the destruction
        MyAuto_Ptr<MyTestObject> p(new MyTestObject("Rahul Singh", 29));

        //test the -> operator
        cout << "Name: " << p->GetName() << ", Age: " << p->GetAge() << " ";

        //test the transfer of ownership in copy constructor
        MyAuto_Ptr<MyTestObject> p2(p);

        //test the * operator
        cout << "Name: " << (*p2).GetName() << ", Age: " << (*p2).GetAge() << " ";

        //test the transfer of ownership in assignment operator
        MyAuto_Ptr<MyTestObject> p3;
        p3 = p2;

        //test the get function
        cout << "Name: " << p3.get()->GetName() << ",
            Age: " << p3.get()->GetAge() << " ";

        //lets test the reset function
        p3.reset(new MyTestObject("Megha Singh", 28));

        //test the get function
        cout << "Name: " << p3.get()->GetName() << ",
            Age: " << p3.get()->GetAge() << " ";

        //finally lets test the release function
        MyAuto_Ptr<MyTestObject> p4(p3.release());

        cout << "Name: " << p4.get()->GetName() << ",
            Age: " << p4.get()->GetAge() << " ";
    }
    getchar();
    return 0;
}






Sponsored Ads



Interview Questions
HR Interview Questions
Testing Interview Questions
SAP Interview Questions
Business Intelligence Interview Questions
Call Center Interview Questions

Databases

Clipper Interview Questions
DBA Interview Questions
Firebird Interview Questions
Hierarchical Interview Questions
Informix Interview Questions
Microsoft Access Interview Questions
MS SqlServer Interview Questions
MYSQL Interview Questions
Network Interview Questions
Object Relational Interview Questions
PL/SQL Interview Questions
PostgreSQL Interview Questions
Progress Interview Questions
Relational Interview Questions
SQL Interview Questions
SQL Server Interview Questions
Stored Procedures Interview Questions
Sybase Interview Questions
Teradata Interview Questions

Microsof Technologies

.Net Database Interview Questions
.Net Deployement Interview Questions
ADO.NET Interview Questions
ADO.NET 2.0 Interview Questions
Architecture Interview Questions
ASP Interview Questions
ASP.NET Interview Questions
ASP.NET 2.0 Interview Questions
C# Interview Questions
Csharp Interview Questions
DataGrid Interview Questions
DotNet Interview Questions
Microsoft Basics Interview Questions
Microsoft.NET Interview Questions
Microsoft.NET 2.0 Interview Questions
Share Point Interview Questions
Silverlight Interview Questions
VB.NET Interview Questions
VC++ Interview Questions
Visual Basic Interview Questions

Java / J2EE

Applet Interview Questions
Core Java Interview Questions
Eclipse Interview Questions
EJB Interview Questions
Hibernate Interview Questions
J2ME Interview Questions
J2SE Interview Questions
Java Interview Questions
Java Beans Interview Questions
Java Patterns Interview Questions
Java Security Interview Questions
Java Swing Interview Questions
JBOSS Interview Questions
JDBC Interview Questions
JMS Interview Questions
JSF Interview Questions
JSP Interview Questions
RMI Interview Questions
Servlet Interview Questions
Socket Programming Interview Questions
Springs Interview Questions
Struts Interview Questions
Web Sphere Interview Questions

Programming Languages

C Interview Questions
C++ Interview Questions
CGI Interview Questions
Delphi Interview Questions
Fortran Interview Questions
ILU Interview Questions
LISP Interview Questions
Pascal Interview Questions
Perl Interview Questions
PHP Interview Questions
Ruby Interview Questions
Signature Interview Questions
UML Interview Questions
VBA Interview Questions
Windows Interview Questions
Mainframe Interview Questions


Copyright © 2001-2024 Vyoms.com. All Rights Reserved. Home | About Us | Advertise With Vyoms.com | Jobs | Contact Us | Feedback | Link to Us | Privacy Policy | Terms & Conditions
Placement Papers | Get Your Free Website | IAS Preparation | C++ Interview Questions | C Interview Questions | Report a Bug | Romantic Shayari | CAT 2024

Fresher Jobs | Experienced Jobs | Government Jobs | Walkin Jobs | Company Profiles | Interview Questions | Placement Papers | Companies In India | Consultants In India | Colleges In India | Exams In India | Latest Results | Notifications In India | Call Centers In India | Training Institutes In India | Job Communities In India | Courses In India | Jobs by Keyskills | Jobs by Functional Areas

Testing Articles | Testing Books | Testing Certifications | Testing FAQs | Testing Downloads | Testing Interview Questions | Testing Jobs | Testing Training Institutes

Gate Articles | Gate Books | Gate Colleges | Gate Downloads | Gate Faqs | Gate Jobs | Gate News | Gate Sample Papers | Gate Training Institutes

MBA Articles | MBA Books | MBA Case Studies | MBA Business Schools | MBA Current Affairs | MBA Downloads | MBA Events | MBA Notifications | MBA FAQs | MBA Jobs
MBA Job Consultants | MBA News | MBA Results | MBA Courses | MBA Sample Papers | MBA Interview Questions | MBA Training Institutes

GRE Articles | GRE Books | GRE Colleges | GRE Downloads | GRE Events | GRE FAQs | GRE News | GRE Training Institutes | GRE Sample Papers

IAS Articles | IAS Books | IAS Current Affairs | IAS Downloads | IAS Events | IAS FAQs | IAS News | IAS Notifications | IAS UPSC Jobs | IAS Previous Question Papers
IAS Results | IAS Sample Papers | IAS Interview Questions | IAS Training Institutes | IAS Toppers Interview

SAP Articles | SAP Books | SAP Certifications | SAP Companies | SAP Study Materials | SAP Events | SAP FAQs | SAP Jobs | SAP Job Consultants
SAP Links | SAP News | SAP Sample Papers | SAP Interview Questions | SAP Training Institutes |


Copyright ©2001-2024 Vyoms.com, All Rights Reserved.
Disclaimer: VYOMS.com has taken all reasonable steps to ensure that information on this site is authentic. Applicants are advised to research bonafides of advertisers independently. VYOMS.com shall not have any responsibility in this regard.