我已经实现了一个智能指针类,当我尝试编译时,它停在特定的行上,我得到这个消息:在 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/