简单地说:如果我将 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 :/";
}
在 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/