Last active
March 16, 2017 22:30
-
-
Save IvanVergiliev/5a6341bc83b6bde7f734ed907c0ebb43 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 { | |
std::free(pointer); | |
} | |
void* operator new[](std::size_t size) { | |
printf("Calling new[](%zu).\n", size); | |
return std::malloc(size); | |
} | |
void operator delete[](void* pointer) noexcept { | |
std::free(pointer); | |
} | |
/** | |
* 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: http://blogs.msmvps.com/gdicanio/2016/11/17/the-small-string-optimization/ | |
* 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