C++ 静态数组初始化 : does inline initialization reserve space?

标签 c++ arrays static avr volatile

在C++中,下面两个声明是否等价?

static volatile uint16_t *ADCReadings = (uint16_t[64]){0};

static volatile uint16_t ADCReadings[64] = {0};

我正在为 AVR 上的 ISR 内部和外部使用的缓冲区保留空间。但是,尽管这很有趣,但我并不是想知道这是否是最好的方法 - 我想知道这两个声明之间的区别(如果有的话)是什么,以便我能更好地理解这一点.

我知道这两个不同的声明会产生不同大小的二进制文件,因此编译器似乎以不同的方式对待它们。

最佳答案

Are the following two declarations equivalent?

没有。 (uint16_t[64]){0} 是一个临时数组(复合文字*),如果您尝试编译第一行,您将收到不言自明的警告/错误:

warning: temporary whose address is used as value of local variable 'ADCReadings' will be destroyed at the end of the full-expression (Clang)

error: taking address of temporary array (Gcc)

所以,在第一行中,ADCReadings 变成了一个悬空指针。将其用作指向缓冲区的指针会调用未定义的行为。

Gcc 手册 reads :

In C, a compound literal designates an unnamed object with static or automatic storage duration. In C++, a compound literal designates a temporary object that only lives until the end of its full-expression. As a result, well-defined C code that takes the address of a subobject of a compound literal can be undefined in C++, so G++ rejects the conversion of a temporary array to a pointer.


Is this true even at global scope?

在这种情况下,Gcc 和 Clang 不会产生警告/错误。 Gcc 手册进一步阅读:

As an optimization, G++ sometimes gives array compound literals longer lifetimes: when the array either appears outside a function or has a const-qualified type. ... if foo were a global variable, the array would have static storage duration. But it is probably safest just to avoid the use of array compound literals in C++ code.

所以看起来在全局范围内 ADCReadings 不会悬空。

I do know that the two different declarations produce different sized binaries

在第一种情况下,复合文字数组进入.bss部分,ADCReadings进入.data部分:

0000000000004040 l     O .bss   0000000000000080     ._0
0000000000004010 g     O .data  0000000000000008     ADCReadings

ADCReadings 是指向 ._0 的指针。

在第二种情况下,ADCReadings直接进入.bss:

0000000000004040 g     O .bss   0000000000000080     ADCReadings

这也转化为如何使用 ADCReadings。以下简单函数:

uint16_t* foo() {
    return ADCReadings;
}

编译成:

push   rbp
mov    rbp,rsp
mov    rax,QWORD PTR [rip+0x2ed8]        # 4010 <ADCReadings>
pop    rbp
ret    

push   rbp
mov    rbp,rsp
lea    rax,[rip+0x2f08]        # 4040 <ADCReadings>
pop    rbp
ret    

* Compound literals不是标准 C++ 的一部分,一些编译器(Gcc、Clang)允许它们作为扩展。

关于C++ 静态数组初始化 : does inline initialization reserve space?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63067409/

相关文章:

c++ - 使用 Protocol Buffers 更快反序列化的建议

C++ - 如果抛出异常,是否释放本地对象?

arrays - 使用 FasterCSV 将不均匀的行转换为列

c++ - 为什么在内联构造函数中访问静态成员时链接器失败

java - 无法在类外访问正确的类对象

c++ - 指向具有显式构造函数的对象的指针

c++ - 如何获得结构或类的尾随填充的大小?

javascript - 返回包含另一个数组中的阶乘数的数组

javascript - 我可以在 javascript 中将数组附加到 'formdata' 吗?

c++ - 定义 const 变量的最佳方式