Smart pointers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mansi
    New Member
    • Sep 2006
    • 2

    Smart pointers

    Hi,

    What r smart pointers in c++ and why do we use them?
  • anupam
    New Member
    • Aug 2006
    • 12

    #2
    Hello Mansi,

    A smart pointer is a C++ class that mimics a regular pointer in syntax and some semantics, but it does more. Because smart pointers to different types of objects tend to have a lot of code in common, almost all good-quality smart pointers in existence are templated by the pointee type, as you can see in the following code:

    template <class T>
    class SmartPtr
    {
    public:
    explicit SmartPtr(T* pointee) : pointee_(pointe e);
    SmartPtr& operator=(const SmartPtr& other);
    ~SmartPtr();
    T& operator*() const
    {
    ...
    return *pointee_;
    }
    T* operator->() const
    {
    ...
    return pointee_;
    }
    private:
    T* pointee_;
    ...
    };

    SmartPtr<T> aggregates a pointer to T in its member variable pointee_. That's what most smart pointers do. In some cases, a smart pointer might aggregate some handles to data and compute the pointer on the fly.

    The two operators give SmartPtr pointer-like syntax and semantics. That is, you can write

    class Widget
    {
    public:
    void Fun();
    };

    SmartPtr<Widget > sp(new Widget);
    sp->Fun();
    (*sp).Fun();

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      The reason for using them is that they are able to garbage collect themselves. That is when the pointer goes out of scope the data pointed to is automatically deleted with the user having to remember to delete them themselves.

      Personally it sounds like a excuse to write sloppy code to me.

      Comment

      Working...