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

hak*_*8or 6 c++ embedded gcc iterator stl

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

这些都是从GCC-臂无- EABI-4_9工具链窗口使用的Kinetis设计工作室在这里使用了以下标志.

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"
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

小智 1

在一个(或两个)C++ 标准之前,使用指针实现迭代器是合法的。(您可以在标准中搜索“删除黄鼠狼措辞”以了解更多信息。)较新的标准对迭代器的要求更高,例如,如果在同一类型的两个容器中有两个相应的迭代器,那么也可以交换这两个容器需要交换这两个迭代器(如果您愿意,请参阅 N4527 23.2.1 脚注 9 自行阅读)。所有这些意味着使用索引而不是迭代器对容器进行索引肯定会更有效。只是并非所有标准容器类型都支持这一点......这也是使用迭代器增加代码大小的原因。