Code guide

Generate UUIDs in C++

Generate UUIDs in C++ using Boost.UUID, with random v4 generation and string conversion examples.

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";
}

FAQ

Generate UUIDs in C++ questions

Does C++ have a standard UUID type?

No. The C++ standard library has no UUID type, so Boost.UUID or a platform library is commonly used.

Is Boost.UUID random secure?

random_generator uses a strong random source by default, which is suitable for identifiers.

How do I convert a Boost UUID to a string?

Call boost::uuids::to_string(id) to get the canonical lowercase form.

Primary references

Standards and technical sources

The implementation and guidance on this page are checked against these standards and platform documentation sources.

Generate UUID in C++ - Boost.UUID Examples