c++ - 实践中的 union 、别名和类型双关语 : what works and what does not?

标签 c++ gcc strict-aliasing

我无法理解使用带有 GCC 的 union 可以做什么和不可以做什么。我阅读了有关它的问题(特别是 herehere ),但它们关注的是 C++ 标准,我觉得 C++ 标准和实践(常用的编译器)之间存在不匹配。

特别是,我最近在 GCC online doc 中发现了令人困惑的信息。在阅读编译标志 -fstrict-aliasing 时。它说:

-fstrict-aliasing

Allow the compiler to assume the strictest aliasing rules applicable to the language being compiled. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an unsigned int can alias an int, but not a void* or a double. A character type may alias any other type. Pay special attention to code like this:

union a_union {
  int i;
  double d;
};

int f() {
  union a_union t;
  t.d = 3.0;
  return t.i;
}

The practice of reading from a different union member than the one most recently written to (called “type-punning”) is common. Even with -fstrict-aliasing, type-punning is allowed, provided the memory is accessed through the union type. So, the code above works as expected.

这是我认为我从这个例子和我的疑惑中理解的:

1)别名仅适用于相似类型或字符之间

1) 的后果: 别名——顾名思义——是当你有一个值和两个成员来访问它时(即相同的字节);

疑问:当它们具有相同的字节大小时,两种类型是否相似?如果不是,类似的类型有哪些?

1) 的结果对于不相似的类型(无论这意味着什么),别名不起作用;

2) 类型的双关语是指我们读到的成员与我们写信的成员不同;这很常见,只要通过 union 类型访问内存,它就可以按预期工作;

疑问: 是在类型相似的类型双关语中使用别名吗?

我很困惑,因为它说 unsigned int 和 double 不相似,所以别名不起作用;然后在示例中它是 int 和 double 之间的别名,它清楚地表明它按预期工作,但称之为类型双关语: 不是因为类型相似或不相似,而是因为它是从它没有写入的成员中读取的。但是从它没有写的成员那里读取是我理解别名的用途(正如这个词所暗示的那样)。我迷路了。

问题: 有人可以澄清别名和类型双关语之间的区别以及这两种技术的哪些用途在 GCC 中按预期工作?编译器标志有什么作用?

最佳答案

别名可以从字面上理解它的含义:当两个不同的表达式引用同一个对象时。类型双关是“双关”一个类型,即将某种类型的对象用作不同的类型。

形式上,类型双关语是未定义的行为,只有少数异常(exception)。当您不小心摆弄比特时,通常会发生这种情况

int mantissa(float f)
{
    return (int&)f & 0x7FFFFF;    // Accessing a float as if it's an int
}

异常(exception)情况是(简化的)

  • 将整数作为无符号/有符号对应物访问
  • charunsigned charstd::byte
  • 的形式访问任何内容

这被称为严格别名规则:编译器可以安全地假设两个不同类型的表达式永远不会引用同一个对象(上述异常(exception)除外),因为否则它们将具有未定义的行为。这有助于优化,例如

void transform(float* dst, const int* src, int n)
{
    for(int i = 0; i < n; i++)
        dst[i] = src[i];    // Can be unrolled and use vector instructions
                            // If dst and src alias the results would be wrong
}

gcc 说的是它稍微放宽了规则,并允许通过 union 进行类型双关,即使标准不需要它

union {
    int64_t num;
    struct {
        int32_t hi, lo;
    } parts;
} u = {42};
u.parts.hi = 420;

这是类型双关语 gcc 保证将起作用。其他情况可能看起来有效,但有一天可能会默默地被打破。

关于c++ - 实践中的 union 、别名和类型双关语 : what works and what does not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762186/

相关文章:

c++ - 关于 "circular reference",我使用了 weak_ptr 但内存泄漏仍然发生

c++ - 相邻数组元素的地址之间的差异..?

c++ - Mingw-w64 和 TDM-GCC 一个简单的 GDI 项目的区别

c - GCC依赖问题

pointers - gcc C/C++ 假设没有指针别名

c++ - 变量中内存的简单重叠是否违反了别名规则?

c++ - 在 C++ 中使用 sprintf 和 std::string

c++ - 在 opencv 中使用网络摄像头未显示图像

c++ - 在 C++ 中, "access"在严格的别名规则中是什么意思?

c - 严格的别名规则是什么?