class template pointer type destructor error visual studio 2015 v140

-1

I want to implement a generic data structure using a class template with pointer types. When i want to use the operator+ program gives "Access violation reading location" error (which is given below). The minimum working code is given.

This is the main definition

template <class T>
class Data
{
  public:
     Data() {}  
     ~Data() {}

  public:
  T m_value;
};

//This is the specialization for pointer types
template <class T>
class Data<T*>
{
 public:
    Data()  { m_value = new T();} 
    //~Data() {delete m_value;}   ********This gives error***
    ~Data() {}                   //****** This works 

    Data(const T value)  { m_value = new T(value); }

    template <class T>
    friend Data<T*> operator+(Data<T*> a, Data<T*> b);

    Data<T*>& operator=(const Data<T*> value);

 public:
    T* m_value;
};


//friend operator+
template <class T>
Data<T*> operator+(Data<T*> a, Data<T*> b)
{ 
    Data<T*> temp(*a.m_value + *b.m_value);
    return temp;
}

//member operator=
template <class T>
Data<T*>& Data<T*>::operator=(const Data<T*> value)
{
    if (!this->m_value)
        this->m_value = new T();

    *this->m_value = *value.m_value;
    return *this;
}

Error on the line : operator+ (which calls destructor above)

void main()    
{
    typedef Data<int *> Data_Int;

    Data_Int dt1(100);
    Data_Int dt2(200);
    Data_Int dt3;

    dt3 = dt1 + dt2; // error line              

}

Error occurs at operator delete

void __CRTDECL operator delete(void* const block) noexcept
{
    #ifdef _DEBUG
    _free_dbg(block, _UNKNOWN_BLOCK); //Error line 
    #else
    free(block);
    #endif
}

error output

Exception thrown at 0x5CF33B8D (ucrtbased.dll) in Deneme.exe: 0xC0000005: Access violation reading location 0x006E0069.

If there is a handler for this exception, the program may be safely continued.

Any help would be appreciated...

c++
class
pointers
templates
operator-overloading
asked on Stack Overflow Feb 17, 2019 by Tanzer • edited Feb 18, 2019 by Tanzer

1 Answer

0

Fortunately i realized that it was a simple error. The proper copy constructor was missing, so the compiler naturally made an implicit one and made pointer to pointer assignment which is the source of the error.

So the correct copy constructor for the above code is

Data(const Data<T*> & copy) { data_ptr = new T(*copy.data_ptr); }
answered on Stack Overflow Feb 18, 2019 by Tanzer

User contributions licensed under CC BY-SA 3.0