Determine the maximal length of the strings falling under the Small String Optimization of your standard library

January 3, 2024 ยท View on GitHub

#include #include #include

template struct failing_alloc : public std::allocator { using value_type = T; failing_alloc() = default; template failing_alloc(failing_alloc const&) {} template struct rebind { typedef failing_alloc 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 const&, failing_alloc const&) { return true; }

template <typename T, typename U> inline bool operator != (failing_alloc const& a, failing_alloc 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;

}