gpt4 book ai didi

c++ - 是结构{} x;匿名结构?

转载 作者:太空狗 更新时间:2023-10-29 23:39:51 25 4
gpt4 key购买 nike

Clang、GCC 和 Visual Studio 2013 提示这段代码。

struct { };

Clang 与 -Weverything:

warning: anonymous structs are a GNU extension [-Wgnu-anonymous-struct]

带有 -Wall -Wextra -pedantic 的 GCC:

warning: ISO C++ prohibits anonymous structs [-Wpedantic]

带有 /W4 的 Visual Studio 2013:

warning C4094: untagged 'struct' declared no symbols

只要我添加一个变量声明,警告就会消失。

struct { } x;

所有三个都提示一个未使用的变量。

我假设这仍然是一个匿名结构和非法 C++,并且编译器出于某种原因停止警告。但由于该行为在三个独立的编译器中仍然存在,我想知道添加变量声明是否会以某种方式改变程序的语义。


如果这是一个非法程序,-pedantic-errors 不会导致 Clang 或 GCC 产生编译错误。与 Visual Studio 类似,/Za 应该强制出现编译错误,但事实并非如此。

最佳答案

如果将字段添加到结构中,区别就很明显了。

struct A {
// Anonymous struct
struct {
int x;
};
};

struct B {
// Not an anonymous struct
struct {
int x;
} y;
};

使用匿名结构,您可以通过编写a.x 来访问A ax 字段。

使用命名结构,您必须通过编写 b.y.x 来访问 B bx

匿名结构是 C11 标准的一部分,它们是各种编译器(包括 GCC 和 MSVC)中可用的通用扩展。由于它们在 C++ 中是非标准的,因此启用迂腐警告将触发诊断。这正是学究式警告旨在实现的目的。

Anonymous ≠ unnamed(什么是匿名结构?)

结构声明也可以声明变量。该结构的名称称为“标签”。省略两者会创建一个匿名结构。

(注意:这些示例是说明性的。它们不是完整或正确的代码片段。)

// Structure tag is "A", declares a variable named "x".
struct A { int field; } x;
x.field = 7;
A y;
y.field = 8;

// Structure tag is "B", no variables declared.
struct B { int field; };
B x;
x.field = 10;

// Structure has no tag, declares a variable named "y".
struct { int field; } y;
y.field = 12;

// Structure has no tag and declares no variable...
// therefore, it is an "anonymous struct".
// The contents are accessible from "outside" the structure.
struct { int field; };
field = 10;

在 MSVC 中,您还可以通过以下方式创建匿名结构,但这是非标准的(GCC 通过 -fms-extensions 支持):

struct A { int x };
struct B { struct A; int y; };
// B has two fields, x and y.

“匿名结构”的定义在 N1570 §6.7.2.1 第 13 段中给出,

An unnamed member whose type specifier is a structure specifier with no tag is called an anonymous structure

关于c++ - 是结构{} x;匿名结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27644728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com