C++ has no standard UUID type, so most projects use Boost.UUID, a mature header library that generates and formats UUIDs.
Key takeaways
- Boost.UUID is the common choice for C++ UUIDs.
- random_generator produces a version 4 UUID.
- to_string converts a UUID to canonical text.
For implementation context, continue with UUID v4, UUID Versions, and Go. These pages cover the closest generator, comparison, validation or storage decisions without repeating this guide.
Generate a random UUID with Boost
Create a random_generator once and call it to produce version 4 values, then convert to a string for output or storage.
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <iostream>
int main() {
boost::uuids::random_generator gen;
boost::uuids::uuid id = gen(); // version 4
std::cout << boost::uuids::to_string(id) << "\n";
}Parse a UUID string
Use the string generator to parse canonical text into a uuid, which throws on clearly invalid input.
#include <boost/uuid/string_generator.hpp>
boost::uuids::string_generator parse;
boost::uuids::uuid id = parse("018f2f7a-07b2-7d6e-9c37-43e1577b8b44");Catch malformed input at the boundary
Boost string_generator reports invalid text with an exception. Catch it at the request or import boundary and return a validation error. The parser accepts more than one text representation, so a strict canonical contract also needs a comparison with to_string().
Keep the uuid value internally instead of repeatedly parsing strings. Reuse a generator according to its documented threading requirements, and do not reseed a pseudo-random engine with a timestamp for each identifier.
#include <stdexcept>
try {
boost::uuids::string_generator parse;
auto id = parse("invalid-input");
std::cout << boost::uuids::to_string(id) << "\n";
} catch (const std::runtime_error&) {
std::cerr << "Invalid UUID text\n";
}