C++ 类指针用 reinterpret_cast 转换为 --int64 的问题


代码声明如下:


 #ifdef _WIN64
typedef unsigned __int64    MEAS_ID;
#else
typedef unsigned long   MEAS_ID;
#endif

//类
class className
{};

//单向链表
struct ListLink{
    MEAS_ID AddressVale;
    className* pClass;
    ListLink* pNext;
};
function: MEAS_ID createclass(){
    MEAS_ID retval;
    className* pClass = new className();
    retval = reinterpret_cast<MEAS_ID>(pClass);

    //将对象增加到链表内
    ListLink* pLink = new ListLink;
    pLink->AddressVale = retval;
    pLink->pClass = pClass;
    pLink->pNext = NULL;
    pLinkList->CreateLink(pLink);
    return retval;
}

function: // 删除链表内对象
int DeleteLink(MEAS_ID &iNo){
    ListLink* pPre = m_pMeasHead;
    ListLink* pCur = pPre->pNext;
    int retval = -1;
    while(pCur){
        if(pCur->AddressVale==iNo){
            pPre->pNext = pCur->pNext;
            if(pPre->pNext == NULL) m_pMeasTail = pPre;
            delete pCur->pMeas;
            pCur->pMeas = NULL;
            delete pCur;
            retval = 0;
            iNo = 0;

            break;
        }
        pPre = pCur;
        pCur = pPre->pNext;
    }

return retval;
}

问题出现在从链表中删除对象,如果 MEAS_ID unsigned --int64 的话 while 循环内 pCur->AddressVale==iNo 判断结果为 FALSE,而如果 MEAS_ID unsigned long 的话,其判断结果为 TRUE,请问是什么问题?

指针 C++

khxooo 10 years, 3 months ago
  1. 不知道你在干什么,明明是C++,非要拿来当C用。
  2. C++从来没保证过reinterpret_cast之后的结果能拿来做任何事,除非是再reinterpret_cast回原来的类型。
  3. unsigned __int64 是个很傻的类型,用 uint64_t ,在你的例子中,应该用 uintptr_t ,虽然你可能以为它们是一样的,但是真的不一样。
玖玖京京京玖京 answered 10 years, 3 months ago

Your Answer