2

Please have a look at the code below. Is this a smart pointer? If so, why the first object, p1, is dangling at the end of the code? (That is p2 is deleted by the destructor but p1 remains, why?)

#include <iostream>
#include <vector>
using namespace std;

template <class T> class my_auto_ptr {
    T* myptr;

public:
    my_auto_ptr(T* ptr = 0) : myptr(ptr) { }

    ~my_auto_ptr() {
        delete myptr;
    }

    T* operator ->() const {
        if (myptr != nullptr)  return myptr;
        else throw runtime_error("");
    }
    T& operator* () const {
        if (myptr != nullptr)  return *myptr;
        else throw runtime_error("");
    }
    T* release() {
        T* rptr = myptr;
        myptr = 0;
        return rptr;
    }
};

//----------------------------------

int main() try {
    my_auto_ptr<vector<int> > p1(new vector<int>(4, 5));
    cout << p1->size() << endl;

    my_auto_ptr<int> p2(new int(6));
    cout << *p2 << endl;

    return 0;
}

//-------------------------------

catch (...) {
    cerr << "Exception occurred.\n";
    return 1;
}
Alan Farner
  • 31
  • 1
  • 4

1 Answers1

7

Is this a smart pointer?

No. It is copyable and assignable, but performing either of those operations will result in multiple deletes. You need to make sure that it is either non-copyable and non-assignable, or that it implements the rule of 3 or 5.

MrTux
  • 28,370
  • 24
  • 91
  • 123
juanchopanza
  • 210,243
  • 27
  • 363
  • 452