TheMemberFormerlyKnownAsAWOL:
std:string doesn't turn your heap into Swiss cheese.
Robin2:
std:string treats strings (cstrings) as char arrays terminated with a NULL ('\0'). In the small memory of an Arduino the size of these arrays should be defined at compile time so the exact amount of memory, and the location in memory is pre-defined.
Both of these statements are incorrect.
String
and std::string
both dynamically allocate memory, and will both cause heap fragmentation.
They are just different implementations of the same principle. std::string
is the most commonly used version, as it is part of the official C++ standard. However, on AVR Arduinos, you cannot use the C++ Standard Template Library (STL), so you cannot use std::string
. That's why Arduino created its own String
class, and this is the most widely used version in the Arduino ecosystem.
While both string classes use dynamic memory, most implementations of std::string
have Small String Optimizations (SSO), where small strings are allocated on the stack instead of the heap. This can slightly reduce the amount of fragmentation caused by the strings.
The best string implementation to use on microcontrollers with limited RAM is null-terminated character arrays, allocated on the stack. The stack data structure ensures that memory is deallocated in the reverse order of the allocations, which makes fragmentation impossible. These strings are often referred to as "c-strings".
Pieter