为什么C ++不允许匿名结构? [英] Why does C++ disallow anonymous structs?

查看:87
本文介绍了为什么C ++不允许匿名结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些C ++编译器允许匿名联合和结构作为标准C ++的扩展。这是一种语法糖,有时非常有帮助。

Some C++ compilers permit anonymous unions and structs as an extension to standard C++. It's a bit of syntactic sugar that's occasionally very helpful.

阻止该标准成为标准的原因是什么?有技术障碍吗?哲学的?还是只是没有足够的理由来证明这一点?

What's the rationale that prevents this from being part of the standard? Is there a technical roadblock? A philosophical one? Or just not enough of a need to justify it?

这里是我正在谈论的示例:

Here's a sample of what I'm talking about:

struct vector3 {
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float v[3];
  };
};

我的编译器会接受此操作,但是它会警告无名结构/联合是对C ++的非标准扩展。

My compiler will accept this, but it warns that "nameless struct/union" is a non-standard extension to C++.

推荐答案

正如其他人指出的那样,标准C ++中允许匿名联合,但匿名结构则不允许。

As others have pointed out anonymous unions are permitted in standard C++, but anonymous structs are not.

这样做的原因是C支持匿名联合,但不支持匿名结构*,因此C ++支持前者以实现兼容性,但不支持后者,因为不需要兼容性。

The reason for this is that C supports anonymous unions but not anonymous structs*, so C++ supports the former for compatibility but not the latter because it's not needed for compatibility.

此外,C ++中的匿名结构用处不大。您演示的用法具有一个包含三个浮点数的结构,可以用 .v [i] .x .y .z ,我相信会导致C ++中的行为不确定。 C ++不允许您写一个联合成员,例如 .v [1] ,然后再读另一个成员,例如 .y 。尽管执行此操作的代码并不罕见,但实际上定义不正确。

Furthermore, there's not much use to anonymous structs in C++. The use you demonstrate, to have a struct containing three floats which can be referred to either by .v[i], or .x, .y, and .z, I believe results in undefined behavior in C++. C++ does not allow you to write to one member of a union, say .v[1], and then read from another member, say .y. Although code that does this is not uncommon it is not actually well defined.

C ++的用户定义类型工具提供了替代解决方案。例如:

C++'s facilities for user-defined types provide alternative solutions. For example:

struct vector3 {
  float v[3];
  float &operator[] (int i) { return v[i]; }
  float &x() { return v[0]; }
  float &y() { return v[1]; }
  float &z() { return v[2]; }
};

* C11显然添加了匿名结构,因此将来对C ++的修订可能会添加它们。 / sub>

* C11 apparently adds anonymous structs, so a future revision to C++ may add them.

这篇关于为什么C ++不允许匿名结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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