有没有办法检查指针是否悬空?

2022-01-12 00:00:00 pointers c++ mfc dangling-pointer

我有一个代码,我使用指针来访问一些数据块.在极少数情况下,数据块的一些成员是空的,因此指针变得悬空.事实上,我得到了正确的指针,但是当试图用指针做某事时程序崩溃了.

I have a code where I use a pointer to access some datablock. In some rare cases, a few members of the datablock are empty, and as a result the pointer becomes dangling. In fact, I get the correct pointer but the program crashes when trying to do something with the pointer.

通常的建议是避免这种用法.但遗憾的是,我使用的框架要求我使用这种类型的数据访问方法.

The usual advice would be to avoid this type of usage. But sadly, the framework I use requires that I use this type of data access methods.

有没有办法在对指针进行任何操作之前检查"指针是否无效?显然,检查指针是否不等于 NULL 不起作用.我也试过这个:

Is there a way I can "check" if the pointer is invalid before doing any operation with it? Checking that the pointer is not equal to NULL did not work, obviously. I also tried this:

try
{
    CString csClassName = typeid(*pMyPointer).name();  // Check error condition
    // The line below fails due to dangling pointer (data block is not valid).
    hr = pMyPointer->MyPointerMethod(); 
}
catch(bad_typeid)
{
    return E_FAIL;
}
catch(...)
{
    return E_FAIL;
}

方法对吗?

推荐答案

无法检查原始指针是否有效.当您访问它们时,不能保证无效的指针会失败.您需要使用某种形式的智能指针,而不是使用原始指针.

There's no way to check whether or not a raw pointer is valid. Invalid pointers are not guaranteed to fail when you access them. Instead of using a raw pointer, you need to use some form of smart pointer.

相关文章