混合静态和重新解释铸造是不安全的,当铸造和返回从void *? [英] Is it unsafe to mix static and reinterpret cast when casting to and back from void*?

查看:114
本文介绍了混合静态和重新解释铸造是不安全的,当铸造和返回从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):


转换为
a不同类型的对象指针。当类型指针到T1的prvalue v是
转换为类型指向 cv T2的指针时,结果是 static_cast< cv
T2 *> ;如果T1和T2都是标准布局
类型(3.9),并且T2的对齐要求不是更严格的话,则(static_cast cv void *>(v))

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆