Skip to content

Instantly share code, notes, and snippets.



Last active Mar 16, 2017
What would you like to do?
#include <cstdlib>
#include <string>
// All of the below are not really standards-compliant, but good enough
// for experiments.
void* operator new(std::size_t size) {
printf("Calling new(%zu).\n", size);
return std::malloc(size);
void operator delete(void* pointer) noexcept {
void* operator new[](std::size_t size) {
printf("Calling new[](%zu).\n", size);
return std::malloc(size);
void operator delete[](void* pointer) noexcept {
* This is a demo of the small string optimization - the effect of which here is that
* std::to_string will almost never allocate heap memory. In particular, it never does on
* the tested version of clang, and only allocates memory for numbers with more than 15
* digits on G++ 5.0.
* For details, look at this article:
* or many of the others available online.
int main() {
// Comments are about the behaviour with clang-800.0.42.1.
// Yes, this is a memory leak.
auto s = new std::string; // prints "Calling new(24)."
std::string s1; // doesn't print anything.
auto num = std::to_string(1234); // doesn't print anything.
printf("%zu\n", num.length()); // prints "4" and nothing else.
printf("%zu\n", std::to_string(123456789123456789LL).length()); // prints "18" and nothing else.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment