类模板指针类型驱动器错误视觉工作室2015 V140

class template pointer type destructor error visual studio 2015 v140

本文关键字:视觉 工作室 2015 V140 错误 驱动器 指针 类型      更新时间:2023-10-16

我想使用带有指针类型的类模板来实现通用数据结构。当我想使用操作员 程序时,会产生"访问违规读取位置"错误(下面给出)。给出了最低工作代码。

这是主要定义

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;
}

行上的错误:操作员 (上面调用destructor)

void main()    
{
    typedef Data<int *> Data_Int;
    Data_Int dt1(100);
    Data_Int dt2(200);
    Data_Int dt3;
    dt3 = dt1 + dt2; // error line              
}

在操作员删除处发生错误

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

错误输出

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.

任何帮助将不胜感激...

幸运的是,我意识到这是一个简单的错误。缺少正确的复制构造函数,因此编译器自然制作了一个隐式构造函数,并将指针定为指针分配,这是错误的来源。

所以上述代码的正确复制构造函数是

Data(const Data<T*> & copy) { data_ptr = new T(*copy.data_ptr); }