gpt4 book ai didi

c++ - 与 at() 或索引相比,为什么使用 C++ 迭代器会显着增加代码大小?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:15 24 4
gpt4 key购买 nike

我一直在考虑在嵌入式系统(16KB SRAM 和 64KB 闪存,Cortex M4)上使用更新的 C++ 语言功能,例如迭代器,但遇到了令人惊讶的障碍。为什么迭代器如此庞大?我的印象是它们基本上是一些指针运算或索引。 STL 是否引入了一些意外代码?

这些是在 Windows 上使用 Kinetis Design Studio 和来自 here 的 gcc-arm-none-eabi-4_9 工具链使用以下标志。

arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 -Os -fmessage-length=0 -fsigned-char -ffunction-sections -fdata-sections -fsingle-precision-constant -flto  -g3 -I"../Sources" -I"../Includes" -std=gnu++11 -fabi-version=0 -std=c++11 -MMD -MP -MF"Sources/System.d" -MT"Sources/System.o" -c -o "Sources/System.o" "../Sources/System.cpp"

ITM_SendChar 只接受一个字符并将其放入寄存器。

std::string input = "Oh hai there! :D\n";

#ifdef char_array
// .text 7352
// .data 376
// .bss 236
for(int i = 0; i < input.size(); i++)
ITM_SendChar(input[i]);
#endif

#ifdef char_at
// .text 7392
// .data 376
// .bss 236
for(int i = 0; i < input.size(); i++)
ITM_SendChar(input.at(i));
#endif

#ifdef char_itterator
// .text 39744
// .data 384
// .bss 252
for(char some_char : input)
ITM_SendChar(some_char);
#endif

#ifdef char_itterator_auto
// .text 39744
// .data 384
// .bss 252
for(auto some_char : input)
ITM_SendChar(some_char);
#endif

#ifdef char_itterator_auto_no_copy
// .text 39744
// .data 384
// .bss 252
for(auto& some_char : input)
ITM_SendChar(some_char);
#endif

最佳答案

[] 运算符和 .at() 之间的主要区别在于 .at() 会进行边界检查,如果索引超出范围将抛出异常。

您使用的标准库实现似乎很可能在使用迭代器时链接了一些额外的代码。找到原因的唯一方法是检查两个版本的链接器映射文件,并仔细查看您正在使用的函数的源代码,也许还有生成的程序集。

一般来说,如果您需要非常小的代码,您会希望避免使用任何标准库,因为其中的函数可以引入大量代码和数据。即使将命令行解析为 main() 期望的格式的代码也可能相当大。

为了比较,试试这个:

const char *input = "Oh hai there! :D\n";

while (*input)
ITM_SendChar(*input++);

关于c++ - 与 at() 或索引相比,为什么使用 C++ 迭代器会显着增加代码大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938264/

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