将char数组强制转换为其他类型是否违反严格的别名规则? [英] Does casting a char array to another type violate strict-aliasing rules?

查看:121
本文介绍了将char数组强制转换为其他类型是否违反严格的别名规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下两个功能:

int f1()
{
  alignas(int) char buf[sizeof(int)] = {};
  return *reinterpret_cast<int*>(buf);
}

int f2()
{
  alignas(int) char buf[sizeof(int)] = {};
  char* ptr = buf;
  return *reinterpret_cast<int*>(ptr);
}

GCC警告说,第一个违反了严格的混叠规则.但是第二个没问题.

GCC warns that the first violates strict-aliasing rules. But the second is OK.

Clang毫无保留地接受了这两者.

Clang accepts both without complaint.

警告是否合法?

推荐答案

警告是合法的. f2不好(它是未定义的行为),它只是不会引发警告.

The warning is legitimate. f2 is not OK (it is undefined behaviour), it just doesn't provoke the warning.

我怀疑f2不引起警告的原因是:

I suspect the reason that f2 doesn't provoke the warning is that:

int f3()
{
    int i = 0;
    char *ptr = reinterpret_cast<char*>(&i);
    return *reinterpret_cast<int*>(ptr);
}

完全合法.您可以将char*(或void*)用作通用指针"-前提是您在访问之前将其强制转换回正确的类型.海湾合作委员会显然非常谨慎,避免对f3发出警告,但代价是不对f2发出警告.

Is entirely legal. You can use a char* (or a void*) as a "universal pointer" - provided you cast back to the right type before access. GCC is clearly being careful to avoid warning about f3, at a cost of not warning about f2.

Clang无法警告f1f2-但这不是必需的.

Clang is failing to warn about either f1 or f2 - but it is not required to.

这篇关于将char数组强制转换为其他类型是否违反严格的别名规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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