在test.exe中0x00418c38的未处理异常:0xC0000005:访问违反读取位置0xfffffffc

Unhandled exception at 0x00418c38 in test.exe: 0xC0000005: Access violation reading location 0xfffffffc

本文关键字:访问 0xC0000005 读取 0xfffffffc 位置 反读 异常 exe test 0x00418c38 未处理      更新时间:2023-10-16

我已经实现了一个智能指针类,当我试图编译时,它停在特定的行上,我得到这个消息:在test.exe中的0x00418c38未处理的异常:0xC0000005:访问违规读取位置0xfffffffc.

我的代码是:
  template <class T>
class SmartPointer
{
    private:
        T* ptr;
        int* mone;
    public: 
        SmartPointer() : ptr(0), mone(0) //default constructor
        {
            int* mone = new int (1); 
        }
         SmartPointer(T* ptr2) : ptr(ptr2), mone(0)
         {
             int* mone = new int (1);        
         }
        SmartPointer<T>& operator= (const SmartPointer& second) //assignment operator
        {
            if (this!= &second)
            {
                if (*mone==1)
                {
                    delete ptr; 
                    delete mone;
                }
                ptr = second.ptr;
                mone = second.mone;
                *mone++;
            }
            return *this;
        }
        ~SmartPointer() // Destructor
        {
            *mone--;
            if (*mone==0)
            {
                delete ptr;
                delete mone;
            }
        }
};

我也有一个*和&重载函数和复制构造函数。

停在这里:

if (*mone==0)
你能帮我一下吗?thaks
SmartPointer() : ptr(0), mone(0) //default constructor
{
  int* mone = new int (1);  // PROBLEM
}

你在构造函数中声明了一个名为mone的局部变量。这将隐藏具有相同名称的成员变量。因此,您的成员变量是用0(来自初始化列表)初始化的,但从未设置为指向任何对象。

用这个代替:

  mone = new int (1);

或者直接执行:

SmartPointer() : ptr(0), mone(new int(1)) {}

语句*mone++;*mone--;不会做你想做的事情。后缀自增/自减应用于指针,而不是它所指向的对象。也就是说,它们被解析为:

*(mone++);

你需要父母:

(*mone)++;

确保你已经把你的编译器警告打开到最大,clang和g++都表示这些行有问题