Generate UUID in C++

Table of Contents

UUID Type 1

UUID Type 1 generates a UUID based on the MAC address and timestamp. It is also commonly known as a time-based UUID. This type of UUID keeps stable ordering when generated consecutively. Let's see an example of how to generate a Type 1 UUID in C++:

#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

int main() {
    boost::uuids::uuid uuid = boost::uuids::random_generator()();
    std::cout << uuid << std::endl;
    return 0;
}
    

UUID Type 3

UUID Type 3 generates a UUID based on the MD5 hash of a namespace identifier and a name. This type of UUID is deterministic, meaning that it will always generate the same UUID for the same inputs. Here's an example of generating a Type 3 UUID in C++:

#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

int main() {
    std::string name = "example_name";
    boost::uuids::uuid uuid = boost::uuids::name_generator_md5()(boost::uuids::nil_uuid(), name);
    std::cout << uuid << std::endl;
    return 0;
}
    

UUID Type 4

UUID Type 4 generates a random UUID using a pseudo-random number generator. This type of UUID is unpredictable and suitable for generating unique identifiers. Here's an example of generating a Type 4 UUID in C++:

#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

int main() {
    boost::uuids::uuid uuid = boost::uuids::random_generator()();
    std::cout << uuid << std::endl;
    return 0;
}
    

UUID Type 5

UUID Type 5 generates a UUID based on the SHA-1 hash of a namespace identifier and a name. This type of UUID is similar to Type 3 but uses a different hashing algorithm. Here's an example of generating a Type 5 UUID in C++:

#include <iostream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

int main() {
    std::string name = "example_name";
    boost::uuids::uuid uuid = boost::uuids::name_generator_sha1()(boost::uuids::nil_uuid(), name);
    std::cout << uuid << std::endl;
    return 0;
}
    

Summary

In this article, we explored different ways of generating UUIDs in C++. We covered UUID Type 1, Type 3, Type 4, and Type 5. Type 1 uses the MAC address and timestamp, Type 3 and Type 5 are based on namespace and name with different hashing algorithms, and Type 4 generates random UUIDs. Each type has its own use case, so choose the one that suits your requirements. With the help of the Boost UUID library, generating UUIDs in C++ is straightforward and efficient.

References