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

时间:2014-05-24 07:16:41

标签: c++ smart-pointers unhandled-exception

我已经实现了智能指针类,当我尝试编译时,它会在特定行停止并且我收到此消息: 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;
            }
        }
};

我也有*和&amp;重载函数和复制构造函数。

它停在这里:

if (*mone==0)
你能帮我吗? thaks

1 个答案:

答案 0 :(得分:5)

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++);

你需要parens:

(*mone)++;

确保您已将编译器警告打开到最大值,clang和g ++都表示这些行有些可疑。

相关问题