functions like .find(), .rfind(), .find_first_of() return an index if found.
otherwise they return npos.
prefer to use .at() rather than operator[]
operator[] won’t thow. if pos > size, the behaviour is undefined.
.at() will throw std::out_of_range, if pos >= size.
careful with .c_str()
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream>
#include<string>intmain(){std::stringstr="Hi ";autop=str.c_str();str+="Hello World! Hello World! Hello World! Hello World!";std::cout<<p<<'\n';// the behaviour is undefined, if reallocation happens.}
SSO
Short String Optimization
Short strings are stored directly inside the std::string without needing mem alloc.
It saves both mem allocs and cpu cycles.
Buffer’s size depends on compiler and platform.
SSO is just SBO for strings
1
2
3
4
5
6
7
8
9
// std::string looks something like thisstructStringImpl{union{char*heap_ptr;// for large stringscharsso_buffer[15];// for short strings (implementation-defined size)};size_tsize;size_tcapacity;};
SBO
Small Buffer Optimization
A class stores small data directly inside itself, avoiding heap allocation for small sizes (usually a few bytes).
It saves both mem allocs and cpu cycles.
Buffer’s size depends on compiler and platform.
How to detect SBO in action?
Use sizeof(std::function<…>) to check internal buffer size.
Use tools like Valgrind
Overload new and delete to log
std::string_view
#include <string_view>
C++17
Read-only.
A non-owning view of a string.
No allocate/copy memory.
Just pointing the data.
Faster, really faster.
Dangling ref may happen, so be careful!
1
2
3
4
5
6
7
8
std::string_viewsv;{std::stringtemp="hello";sv=temp;}// temp is destroyed so undefined behavior happens.std::cout<<sv<<"\n";
Prefer to use swap functions for strings and containers. It is very efficient as it only changes pointers. Also use STL algorithms as much as possible.
1
2
3
4
5
std::stringstr;// by this, you can read an entire line of text (including spaces)getline(std::cin,str);// Example: str -> Hello World