Is it unsafe to mix static and reinterpret cast wh

2019-07-22 03:31发布

问题:

Simply: If i static_cast a type X* to void*, is it always safe to reinterpret_cast it back to X*?

I am unable to produce any case where this fails for example:

#include <iostream>

struct a
{
    int* m_array;
};

int main()
{
    bool fail = false;

    for(int i = 0; ++i < 5000;)
    {
        a* pA = new a;
        pA->m_array = new int [i+1]; // A new size of data everytime
        pA->m_array[i] = 10;

        void* pvA = static_cast<void*>(pA);
        pA = reinterpret_cast<a*>(pvA);

        if(pA->m_array[i] != 10)
        {
            fail = true;
            break;
        }

        delete []pA->m_array;
        delete pA;
    }

        if(fail)
            std::cout<<"FAILED!!";
        else
            std::cout<<"Never failed :/";
}

Link to compiled example

Gives the result "Never failed :/" in both debug and release mode with vs 2012. However this is most likely undefined behavior. Right?

回答1:

It is well-defined. As per ISO/IEC 14882:2011 [expr.reinterpret.cast]§7 (emphasis mine):

An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void.