c++ - 在从 void* 转换和返回时混合静态和重新解释转换是否不安全?

标签 c++ casting reinterpret-cast

简单地说:如果我将 static_cast 类型 X* 转换为 void*reinterpret_cast 是否总是安全的它回到 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 :/";
}

Link to compiled example

在 vs 2012 的调试和 Release模式下给出结果“Never failed :/”。然而,这很可能是未定义的行为。对吧?

最佳答案

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

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.

关于c++ - 在从 void* 转换和返回时混合静态和重新解释转换是否不安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499683/

相关文章:

c++ - 我可以将键值对的内存映射文件重新解释为映射以便对它们进行排序吗?

c++ - 在不存在的对象上调用成员函数可以正常工作,c++

c++ - Unix 是用 C 还是 C++ 或两者编码的?

c++ - 迷宫求解程序的回溯逻辑错误

c++ - 为什么 `std::remove_cv<_Iter>::type` 不是一个类型?

pointers - 如何将 lParam 转换为多个结构?

c++ - 创建不同类型 DNS 记录的消息

Java - 带返回值的异步方法

android - 如何从Bundle中提取HashMap而不进行强制转换?

c++ - 使用 reinterpret_cast 从 char* 返回 long long