Skip to content

Instantly share code, notes, and snippets.

@ashvardanian
Created January 3, 2024 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashvardanian/c197f15732d9855c4e070797adf17b21 to your computer and use it in GitHub Desktop.
Save ashvardanian/c197f15732d9855c4e070797adf17b21 to your computer and use it in GitHub Desktop.
Determine the maximal length of the strings falling under the Small String Optimization of your standard library
#include <string>
#include <iostream>
#include <cstdlib>
template <typename T = char>
struct failing_alloc : public std::allocator<T> {
using value_type = T;
failing_alloc() = default;
template <class U> failing_alloc(failing_alloc<U> const&) {}
template <typename U> struct rebind { typedef failing_alloc<U> other; };
void deallocate(T*, std::size_t) { }
T* allocate(std::size_t n) {
std::cout << "Allocating " << n << " bytes\n";
std::exit(EXIT_FAILURE);
}
};
template <typename T, typename U>
inline bool operator == (failing_alloc<T> const&, failing_alloc<U> const&) { return true; }
template <typename T, typename U>
inline bool operator != (failing_alloc<T> const& a, failing_alloc<U> const& b) { return !(a == b); }
int main() {
std::cout << "`sizeof(std::string)` = " << sizeof(std::string) << " bytes\n";
using stack_str = std::basic_string<char, std::char_traits<char>, failing_alloc<char>> ;
stack_str str;
for (std::size_t i = 1; i < 100; ++i) {
str.push_back('a');
std::cout << "Appended " << i << " bytes\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment