c++ - 当 sizeof(long) == sizeof(int) 时 long* 和 int* 之间的转换

标签 c++ c++11 type-conversion language-lawyer type-punning

我们通常知道 sizeof(long) != sizeof(int)。但是 (C++11) 标准的哪些部分不允许 long*int* 别名?仅仅是 [conv.ptr] 中的遗漏,[basic.lval] 中的别名规则,还是其他原因?

void f()
{
    static_assert(sizeof(int) == sizeof(long), "");
    long x[] = {1, 2};
    int* y = x; // error: invalid conversion from ‘long int*’ to ‘int*’ [-fpermissive]
}

最佳答案

是的,在[conv.ptr]中被遗漏了适用段落在[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. Converting a prvalue of type "pointer to T1" to the type "pointer to T2" (where T1 and T2 are object types and where the alignment requirements of T2 are no stricter than those of T1) and back to its original type yields the original pointer value. The result of any other such pointer conversion is unspecified.

你必须使用 reinterpret_cast<int*>(...) .


编辑。 我在这次编辑中使评论更加明显,这不是语言律师的问题,而是意图使用指针。我不确定这种担忧是如何产生的,因为很明显可以不问就简单地进行 C-cast,但如果有疑问 - 将指针转换为 int*违反strict aliasing规则。

也就是说,如果您打破了编译器关于不同类型的指针永远不会指向同一内存位置的假设,则可能会出现未定义的行为。

关于c++ - 当 sizeof(long) == sizeof(int) 时 long* 和 int* 之间的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23829696/

相关文章:

c++ - 字符串迭代器不可递减

c++ - 生成用于大规模重构/重命名的 C++ 符号列表

hadoop - Hive 中用于百分比的数据类型是什么?

perl - 在不使用 eval 的情况下从标量变量创建 VSTRING

c++ - 如何使用 std::vector 处理错误?

c# - 关于我的C编程中的逻辑方程

c++ - QObject::connect 和模板导致问题

javascript - 如何使用 javascript 在 Lat Long 和 MGRS 之间进行转换而不依赖于库

c++ - 打印字符数组 C++

c++ - Mat 和 setMouseCallback 函数