本文介绍了混合静态和重新解释铸造是不安全的,当铸造和返回从void *?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单:If i static_cast a type X * void * ,是否总是安全的 reinterpret_cast 回到X *?

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

我无法生产例如:

#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 :/";
}

在调试中给出Never failed:/和发布模式与vs 2012.但是这很可能是未定义的行为。是吗?

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

推荐答案

根据ISO / IEC 14882:2011 [expr.reinterpret.cast]§7(强调我的):

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

这篇关于混合静态和重新解释铸造是不安全的,当铸造和返回从void *?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 08:12