In object-oriented programming still not all the objects are polymorphic. (And they are not polymorphic in Java too.)
#include <iostream> using namespace std; struct Base { Base() { cout << "Base" << " "; } virtual ~Base() { cout << "~Base" << endl; } int i; }; struct Der : public Base { Der() { cout << "Der" << endl; } virtual ~Der() { cout << "~Der" << " "; } int it[10]; // sizeof(Base) != sizeof(Der) }; int main() { Base *bp = new Der; Base *bq = new Der[5]; delete bp; delete [] bq; // this causes runtime error }
Auto_ptr is not able to manage arrays, because the destructor wired-in to call non-array delete.
void f(int n) { auto_ptr<int> p1(new int); auto_ptr<int> p2(new int[n]); ... } // delete and not delete[] for p2
This is a solution to manage arrays by auto_ptr.
#include <memory> #include <iostream> #include <vector> template <typename T> class ArrDelAdapter { public: ArrDelAdapter(T *p) : p_(p) { } ~ArrDelAdapter() { delete [] p_; } // operators like ->, *, etc... private: T* p_; }; struct X { X() { std::cout << "X()" << std::endl; } ~X() { std::cout << "~X()" << std::endl; } }; int main() { std::auto_ptr< ArrDelAdapter<X> > pp(new ArrDelAdapter<X>(new X[10])); return 0; }