gpt4 book ai didi

c++ - C++ 中 "array of unknown bound of T"的外部声明

转载 作者:可可西里 更新时间:2023-11-01 17:59:56 25 4
gpt4 key购买 nike

我使用 g++ (7.1) 和 clang++ (xcode 9.0) 和 -std=c++11 -Wall 编译了以下程序并得到了结果:

g++

0x10052c050
0x10052c040
0x10052c040

clang ++

0x108b74024
0x108b74018
0x108b74018

这意味着 extern int a[];static int a[3]; 声明相同的实体并具有相同的链接(内部链接)。

//a.cpp
#include <stdio.h>
int a[3];
void f()
{
printf("%p\n", (void*)a);
};
//b.cpp
extern void f();
static int a[3];
void g()
{
printf("%p\n", (void*)a);
extern int a[];
printf("%p\n", (void*)a);
}
int main(int argc, char* argv[])
{
f();
g();
return 0;
}

但是,在 C++11 [3.9/6] 中:

... The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points (“array of unknown bound of T” and “array of N T”) are different types. ...

int a[3];int a[]; 是不同的类型,

在 C++11 [3.5/6] 中:

If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage.

“具有相同的名称和类型”不兼容,因此 extern int a[]; 不应接收先前声明的链接(static int a[3];),所以,“否则,如果没有找到匹配的实体,则 block 作用域实体将接收外部链接。”是兼容的。

我的问题是:

  • 为什么编译结果不符合C++11标准的写法?
  • 或者如果我的理解是错误的,那么什么是正确的?

注意:这个问题不同于error: extern declaration of 'i' follows declaration with no linkage

最佳答案

“extern int a[]”没有完全定义“a”。

在@Bob__ 对我的原始帖子发表评论后更新。

我在我尝试过的所有三个编译器上得到了相同的结果(最多更改指针地址)- 谢谢,@Bob__。既然他们都在编译,我们应该说这是需要更新的标准语言吗?

关于c++ - C++ 中 "array of unknown bound of T"的外部声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842813/

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