1

I am implementing the smart pointer and trying to use it vector of pointers so that I don't have to delete the pointers once it goes out of scope. Below is the program that I wrote but it is crashing. Can someone please help me with this?

#include<iostream>
#include<vector>

using namespace std;


template<class T>
class smrtP
{
    T *p;
public:
    smrtP(T* pp = NULL):p(pp) {}
    ~smrtP() { delete p;}

    T& operator*() {return *p;}
    T* operator->() {return p;}
};


class B
{
public:
    virtual void draw() = 0;
    virtual ~B() { cout<<"~B"<<endl; }
};

class D:public B
{
public:
    D() { cout<<"D"<<endl;}
    virtual void draw()
    {
        cout<<"Draw D"<<endl;
    }
    virtual ~D() { cout<<"~D"<<endl; }
};


int main()
{
    typedef smrtP<B> sp;
    vector<sp> v;
    sp ptr(new D());
    v.push_back(ptr);
}
amithreat
  • 51
  • 5

2 Answers2

3

Considering your smart pointer class:

template<class T>
class smrtP
{
    T *p;
public:
    smrtP(T* pp = NULL):p(pp) {}
    ~smrtP() { delete p;}

    T& operator*() {return *p;}
    T* operator->() {return p;}
};

it lacks implementation of copy operations, e.g. copy constructor and copy assignment. You may want to add those.

In addition, you may want to add implementations for move operations (e.g. move constructor and move assignment).

You could also develop a smart pointer (e.g. like std::unique_ptr) that is movable but non-copyable: it will still work with STL containers like std::vector.

You may also want to read about the "Rule of Three/Five/Zero" here and here.

Community
  • 1
  • 1
Mr.C64
  • 41,637
  • 14
  • 86
  • 162
1

You have two copies of the "smart" pointer; ptr, and the copy in the vector. The default assignment operator is simply copying the internal pointer into the copy, so both copies point to the same object. This is bad because both copies try to delete the object, and that can only be done once.

If you are doing this to learn about how to implement smart pointers, I would suggest reading Scott Meyers' effective C++ books. However, if you are writing production code with a modern C++, you should be using std::shared_ptr or std::unique_ptr.

pat
  • 12,587
  • 1
  • 23
  • 52