I like simple and well written C++ libraries, and I’m especially fond of Boost, so I’m going to blog about it some more 🙂
Today I’ll show you how to generate unique IDs using Boost::UUID header only library. There really isn’t much to be said about it other than it’s simple, consists of only few hearer files, and allows you to generate, hash, and serialize unique IDs.
Refer to the documentation for a complete overview. Here’s a sample program that generates and prints a unique ID:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <boost/uuid/uuid.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/uuid_generators.hpp> using namespace std; using namespace boost::uuids; int main(int argc, char** argv) { auto gen = random_generator(); uuid id = gen(); cout << id << endl; return 1; } |
5023e2d9-8008-4142-b1c7-87cda7cb36b3
Program output.
Just be sure you don’t use this way to generate millions of UUIDs in a short time, boost::uuid:s::random_generator constructor is so slooow!
HINT: maybe re-use the same random_generator instance and just call its operator() in this case.
Yes, of course 🙂
I updated the code per your suggestion 😉 thank you.