c++ - test.exe : 0xC0000005: Access violation reading location 0xfffffffc 中 0x00418c38 处的未处理异常

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

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

到此为止:

if (*mone==0)

你能帮帮我吗??谢谢

最佳答案

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

你需要 parent :

(*mone)++;

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

关于c++ - test.exe : 0xC0000005: Access violation reading location 0xfffffffc 中 0x00418c38 处的未处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23842343/

相关文章:

c++ - 连接字节值的超快速方法

docker - 跨 Docker 容器重新启动的持久日志

c# - 尝试读取或写入 protected 内存。这通常表明其他内存已损坏

c# - 处理异常后发生未处理的异常

c++ - ifstream 无法在递归调用中打开

包含在 2 个特定字符之间的 C++ 子字符串

c++ - 如何测试是否删除了 boost 共享内存对象?

c++ - 智能指针(shared_ptr)

c++ - 可以在智能指针管理的内存上创建新的位置吗?

c++ - 如何将对 std::streambuf 的引用传递给需要 std::istream& 的方法?