Thursday, December 8, 2011

Design a smart pointer in C++

Solution Draft:

reference counter should be shared among all the instance of the pointers referring to the same object. So it's better to dynamically allocate a pointer.

4 comments:

  1. Overloaded question.

    Smart respect to what? Can be shared? With a movable constructor? Thread safe? It should be able to point to a vector?

    ReplyDelete
  2. valid questions to start an interview. Make your assumptions and start coding ;)

    ReplyDelete
  3. Let's forget the thread safety, and let's make it sharable, no copy on write, and it doesn't point to a vector;

    template ;
    struct Storage {
    Storage(T* aPointer)
    : thePointer(aPointer),
    theCounter(1)
    {}

    ~Storage() {
    assert(theCounter == 0);
    delete thePointer;
    }

    T* thePointer;
    size_t theCounter;
    }

    template
    class SmartPointer {
    typedef SmartPointer THIS;
    public:
    SmartPointer(T* aPointer)
    :theStorage(new Storage(aPointer))
    {}

    //copy constructor
    SmartPointer(const THIS& aSM)
    :theStorage(aSM.theStorage) {
    ++(theStorage->counter);
    }

    //assignment operator
    SmartPointer& operator=(const THIS& aSM) {
    if (this == &aSm) return *this;
    if (--(theStorage->counter) == 0) {
    delete theStorage;
    }
    theStorage = aSm.theStorage;
    ++(theStorage->counter);
    }

    ~SmartPointer() {
    if (--(theStorage->counter) == 0) {
    delete theStorage;
    }
    }

    const T* operator->() const {
    return theStorage->thePointer;
    }

    T* operator->() {
    return theStorage->thePointer;
    }

    const T& operator*() const {
    return *(theStorage->thePointer)
    }

    T& operator*() {
    return *(theStorage->thePointer)
    }
    private:
    Storage* theStorage;
    };

    ReplyDelete
  4. Worth to read documentation on Qt blogs about Qt smart pointers (note that they were timely evolved),

    http://labs.qt.nokia.com/2009/08/25/count-with-me-how-many-smart-pointer-classes-does-qt-have/

    ReplyDelete