Identity and equality
What you will learn on this page
Section titled “What you will learn on this page”- The three different questions hidden in “are these two the same?”.
- How to write equality and ordering with C++20 defaulted comparisons.
- Why an ID should have its own type, and how to make it a hash-table key.
- Why
operator==on an entity is easy to get wrong, and what to write instead.
Three meanings of “the same”
Section titled “Three meanings of “the same””Given two C++ objects a and b that describe members, “are they the same?”
can mean three different things:
- The same object in memory:
&a == &b. This is about the program, not the domain. Two copies of a member’s record are different objects, even when they describe the same person. - Equal values: every attribute matches. This is the right meaning for value objects: two postal addresses with the same street, town, and postcode are the same address.
- The same identity: they describe the same member, whatever their other attributes say. This is the right meaning for entities. A snapshot taken before a member moved house and the record after the move are the same member.
Most equality bugs are one of these meanings used where another was needed.
Value equality with defaulted comparisons
Section titled “Value equality with defaulted comparisons”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A value object: two addresses with the same parts are the same address.struct PostalAddress { std::string street; std::string town; std::string postcode;
// `= default` asks the compiler to write ==: it compares street, then // town, then postcode, each with std::string's own ==, and is true only // if all three match. != comes free from ==. friend bool operator==(const PostalAddress&, const PostalAddress&) = default;};In C++20, = default on operator== asks the compiler to compare every member
in order, with each member’s own ==. That is exactly value equality, written
in one line, and it stays correct when a member is added later. (Before C++20,
it had to be written by hand, and adding a member without updating it was a
classic bug.) != is provided automatically from ==.
Strong ID types
Section titled “Strong ID types”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A strong ID type: a number with a meaning. A MemberId cannot be mixed up// with a CopyId, or with an arbitrary int, without the compiler noticing.class MemberId {public: // `explicit`: an int does not quietly become a MemberId. You must write // MemberId{1042}, so every place an ID is made is visible. std::uint32_t // is an unsigned 32-bit integer: IDs are never negative. constexpr explicit MemberId(std::uint32_t value) noexcept : value_(value) {} // The number inside, for printing, storing, and hashing. [[nodiscard]] constexpr std::uint32_t value() const noexcept { return value_; }
// Value equality and ordering, generated by the compiler (C++20). // `= default` compares value_, and a defaulted <=> also gives ==, so // MemberId has ==, !=, <, <=, >, and >=. The ordering is what lets it be // a key in std::map or std::set. It compares only two MemberIds, so // comparing a MemberId with a CopyId does not compile. friend constexpr auto operator<=>(const MemberId&, const MemberId&) noexcept = default;
private: std::uint32_t value_;};
// The same shape, for a copy of a book. A separate class, not an alias, so// the compiler treats MemberId and CopyId as unrelated types.class CopyId {public: constexpr explicit CopyId(std::uint32_t value) noexcept : value_(value) {} [[nodiscard]] constexpr std::uint32_t value() const noexcept { return value_; } friend constexpr auto operator<=>(const CopyId&, const CopyId&) noexcept = default;
private: std::uint32_t value_;};An entity’s identity is usually an ID. It is tempting to use a plain int or
std::string for it, but then a member ID, a copy ID, and a count of days are
all the same type, and nothing stops lend(copy_id, member_id) being called with
the arguments the wrong way round. A strong ID type wraps the number in a
class of its own:
- The constructor is
explicit, so anintdoes not silently become aMemberId. Creating one is always visible:MemberId{1042}. MemberIdandCopyIdare unrelated types, so passing one where the other is expected does not compile.- The defaulted
operator<=>provides==,!=,<,<=,>, and>=, all comparing the wrapped value. Ordering is what lets aMemberIdbe a key instd::maporstd::set.
The cost is a few lines per ID type. A small class template, such as Id<Tag>,
can remove the repetition when there are many; Strong types and API
contracts shows one.
Hashing: using an ID as a hash-table key
Section titled “Hashing: using an ID as a hash-table key”std::unordered_map<MemberId, Member> needs to turn a key into a number, its
hash, to choose where to store it. The standard library provides hashes for
built-in types and std::string, but not for your classes. You provide one by
specializing std::hash:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Lets MemberId be a key in std::unordered_map and std::unordered_set.// Equal IDs must give equal hashes; hashing the one field that == compares// guarantees that.//// std::hash is a class template in the standard library: std::hash<T> is a// small object whose call operator turns a T into a std::size_t. `template// <>` begins a specialization: our own version of std::hash for one type,// MemberId. Unordered containers look for exactly this.template <>struct std::hash<lld::identity::MemberId> { // operator() makes the object callable like a function: hasher(id). std::size_t operator()(const lld::identity::MemberId& id) const noexcept { // Reuse the standard hash for the wrapped number: std::hash<...>{} // creates a hasher, and (id.value()) calls it on the number. return std::hash<std::uint32_t>{}(id.value()); }};The rule a hash must follow: if two keys are equal, their hashes must be
equal. (Unequal keys may share a hash. That only slows lookups down a little.)
The simplest way to keep the rule is to hash exactly what == compares. Here,
== compares one number, and the hash hashes that number. If == ignored a
field that the hash included, two equal keys could get different hashes, and a
lookup could fail to find a key that is in the map.
For a key with several fields, the hashes of the fields must be combined. The C++20 standard library has no function for that. A common approach is to mix them with shifts and an exclusive or, but it is easy to do badly. Often a simpler choice is available: give each entity a single ID, and use that as the key.
Entities: compare identity, by name
Section titled “Entities: compare identity, by name”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// An entity: identified by its MemberId, which never changes. It// deliberately has no operator==: "same member?" and "same details?" are// different questions, so each has a function with a clear name.class Member {public: // The ID is set here, once, and no function changes it afterwards. The // name and address are kept, so they are taken by value and moved in. Member(MemberId id, std::string name, PostalAddress address) : id_(id), name_(std::move(name)), address_(std::move(address)) {}
[[nodiscard]] MemberId id() const noexcept { return id_; } [[nodiscard]] const std::string& name() const noexcept { return name_; } [[nodiscard]] const PostalAddress& address() const noexcept { return address_; }
// The details may change; the member stays the same member. void rename(std::string name) { name_ = std::move(name); } void move_to(PostalAddress address) { address_ = std::move(address); }
private: MemberId id_; std::string name_; PostalAddress address_;};
// Identity: are these two objects about the same member? Only the IDs are// compared; the details may differ, for example in an old copy. `inline`// lets a function be defined in a header that several files include.[[nodiscard]] inline bool same_member(const Member& a, const Member& b) noexcept { return a.id() == b.id();}
// State: do they hold the same details? (Useful in tests and when checking// whether an edit changed anything.) The ID is deliberately not compared:// two different people can have the same name and address.[[nodiscard]] inline bool same_details(const Member& a, const Member& b) { return a.name() == b.name() && a.address() == b.address();}Member deliberately has no operator==. “Equal” would have to mean one of
two things, and both are needed:
same_memberanswers the identity question: same ID?same_detailsanswers the state question: same name and address?
Each has a name that says which question it answers, so the reader of
if (same_member(a, b)) does not have to remember what == means for this
class. Note that same_details does not compare IDs. Two different people can
have the same details.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A hash table from ID to member. It can use MemberId as a key only// because of the std::hash<MemberId> specialization in ids.hpp.std::unordered_map<MemberId, Member> members;const MemberId ada_id{1042};// try_emplace(key, args...) builds the Member in place from the rest of// the arguments, as if by Member(ada_id, "Ada", PostalAddress{...}).members.try_emplace(ada_id, ada_id, "Ada", PostalAddress{"1 Mill Lane", "Oxbridge", "OX1"});
// at() finds the entry by key, and throws std::out_of_range if there is// none. `before` is a separate Member, copied from the stored one.const Member before = members.at(ada_id); // a copy: a snapshot of the details// This changes the stored member itself: at() returns a reference to it.// The braces build the new PostalAddress.members.at(ada_id).move_to({"9 River Road", "Oxbridge", "OX4"});// `after` is a reference, so it is the stored member, not another copy.// It stays valid while the entry is in the map; adding entries does not// invalidate references to elements of an unordered_map.const Member& after = members.at(ada_id);
std::cout << std::boolalpha; // print bools as true/false, not 1/0std::cout << "same member: " << same_member(before, after) << '\n';std::cout << "same details: " << same_details(before, after) << '\n';std::cout << "found by ID after moving: " << members.contains(MemberId{1042}) << '\n';std::cout << "MemberId{7} == MemberId{7}: " << (MemberId{7} == MemberId{7}) << '\n';same member: truesame details: falsefound by ID after moving: trueMemberId{7} == MemberId{7}: truebefore is a copy taken before the move. It is still the same member as
after, but it no longer holds the same details. The map, keyed by the ID,
still finds the member after the move, because the key never changes.
Testing identity and equality
Section titled “Testing identity and equality”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Compile-time checks: IDs do not convert to and from each other or int.// static_assert(condition) stops the build if the condition is false, so// these test the types themselves before any test runs.// std::convertible_to<From, To> is a C++20 concept: true if a From converts// to a To without being asked. std::equality_comparable_with<A, B> is true// if `a == b` compiles for an A and a B; std::equality_comparable<T> is true// if two T values can be compared with ==. The `!` means each must be false.static_assert(!std::convertible_to<int, MemberId>);static_assert(!std::convertible_to<CopyId, MemberId>);static_assert(!std::equality_comparable_with<MemberId, CopyId>);static_assert(!std::equality_comparable<Member>); // on purpose: no ==
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure if// the condition is false; LLD_CHECK_EQ(actual, expected) does the same for// `actual == expected` and prints both values when they differ. They come// from the site's small test header, lld_test.hpp.//// Equal IDs are equal, ordered, and hash to the same number. Both kinds of// set keep one copy of each value, so three IDs with one repeated leave two.LLD_TEST(ids_compare_and_hash_by_value) { LLD_CHECK(MemberId{5} == MemberId{5}); LLD_CHECK(MemberId{5} != MemberId{6}); LLD_CHECK(MemberId{5} < MemberId{6}); LLD_CHECK(std::hash<MemberId>{}(MemberId{5}) == std::hash<MemberId>{}(MemberId{5})); const std::unordered_set<MemberId> hashed{MemberId{1}, MemberId{2}, MemberId{1}}; const std::set<MemberId> ordered{MemberId{2}, MemberId{1}, MemberId{2}}; LLD_CHECK_EQ(hashed.size(), std::size_t{2}); LLD_CHECK_EQ(ordered.size(), std::size_t{2});}
// A value: a copy is equal to the original; change one part and it is not.LLD_TEST(addresses_are_equal_by_value) { const PostalAddress a{"1 Mill Lane", "Oxbridge", "OX1"}; PostalAddress b = a; LLD_CHECK(a == b); b.postcode = "OX2"; LLD_CHECK(a != b);}
// Identity survives change: after a rename, the copy taken before is still// the same member, with different details.LLD_TEST(a_member_stays_the_same_member_when_details_change) { Member member(MemberId{1}, "Ada", {"1 Mill Lane", "Oxbridge", "OX1"}); const Member snapshot = member; // a copy of the member as it is now member.rename("Ada Lovelace"); LLD_CHECK(same_member(member, snapshot)); LLD_CHECK(!same_details(member, snapshot));}
// The other direction: equal details do not make two members one member.LLD_TEST(different_members_with_the_same_details_are_different) { const PostalAddress home{"1 Mill Lane", "Oxbridge", "OX1"}; const Member first(MemberId{1}, "Sam Lee", home); const Member second(MemberId{2}, "Sam Lee", home); // two people, same name and home LLD_CHECK(!same_member(first, second)); LLD_CHECK(same_details(first, second));}The static_asserts test the type design itself, at compile time: an int does
not convert to a MemberId, a CopyId is not a MemberId, the two cannot be
compared with each other, and Member has no == at all. If someone later adds
an implicit constructor or an operator==, these lines stop the build. The
runtime tests check that equal IDs hash equally and that both hashed and ordered
containers treat equal IDs as one key, and they test both directions of identity:
the same member with different details, and different members with the same
details.
Common mistakes
Section titled “Common mistakes”- A defaulted
operator==on an entity. It compares every field, so it answers “same details?”, while most callers mean “same member?”. The exercise below shows the bug this causes. - Comparing addresses (
&a == &b) to mean “same member”. Two copies of the record are different objects. Pointer comparison is about memory, not the domain. - A hash that does not match
==. Equal keys with different hashes make lookups fail unpredictably, depending on where each hash places the key. - Plain
intorstd::stringIDs passed through many functions. A swapped pair of arguments compiles and fails at run time, or silently does the wrong thing. - Changing a stored element’s key.
When a requirement changes
Section titled “When a requirement changes”New requirement: “Merge two member accounts that turn out to belong to the same person.”
With identity by ID, the question is precise: which ID survives? Say M-2 is
merged into M-1. Then every loan, hold, and fine that refers to M-2 must be moved
to M-1, and M-2 is closed, perhaps with a note saying where it went. Because IDs
are a distinct type, a search for MemberId finds every place that stores a
reference to a member, which is where references to M-2 may hide. If Member had an operator==
comparing details, there would be a tempting but wrong shortcut, “they are equal
now, so they are the same”, which would also merge two different people who
happened to have the same name and address.
Exercise: Find the equality bug in an entity
This code compiles without warnings. A member edits their e-mail address in a form, and the form saves the edited copy:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED on purpose. A member record: an ID that identifies the member, plus// two details that can change.struct Member { int id; std::string name; std::string email;
// Compares id, name, and email. // `= default` asks the compiler to write ==: it compares the fields in // the order they are declared, and is true only if all three are equal. friend bool operator==(const Member&, const Member&) = default;};
class MemberList {public: // Takes the member by value and moves it to the end of the vector. void add(Member member) { members_.push_back(std::move(member)); }
// Saves an edited copy of a member back into the list. // The intent: replace the stored record for this member, or add it if // the member is new. void save(const Member& edited) { // std::find walks the vector from the start and stops at the first // element that is == edited, returning an iterator to it, or end() // if none is. The == it uses is Member's operator== above. const auto found = std::find(members_.begin(), members_.end(), edited); if (found != members_.end()) { // `*found` is the stored element; this copies `edited` over it. *found = edited; } else { // No stored element was == edited. members_.push_back(edited); // "a new member" } }
[[nodiscard]] std::size_t size() const { return members_.size(); }
private: std::vector<Member> members_;};
int main() { MemberList list; list.add({1042, "Ada", "ada@example.org"});
// `{1042, "Ada", "ada@example.org"}` fills the three fields in order. Member edited{1042, "Ada", "ada@example.org"}; // loaded into an edit form edited.email = "ada@lovelace.example"; // the member changes it // The question for the exercise: which branch of save() runs here? list.save(edited);
// main's return value is the list's size, turned from std::size_t into // int, so the answer can be seen as the program's exit code. return static_cast<int>(list.size()); // how many members now?}- How many members does the list hold after
save, and why? - What is the design mistake, as opposed to the line that fails?
- Fix it.
Show the explained answer
-
Two.
savelooks for the stored member withstd::find, which usesoperator==. The defaulted==compares the ID, the name, and the e-mail. The edited copy has a new e-mail, so it equals nothing in the list, andsaveappends it as “a new member”. The list now holds member 1042 twice, with the old and the new address. (Run once by hand while writing this page, the program returned 2.) Nothing crashes, so the bug can go unnoticed until two records disagree. -
The entity’s equality means “same details”, but the code needs “same member”. The defaulted
==was a natural thing to write, because it is correct for values. For an entity, it answers the wrong question, and every standard algorithm that uses==(std::find,std::count,std::remove) inherits that meaning silently. -
Compare identity explicitly, and remove the misleading
==:struct Member {int id; // better: a MemberId strong typestd::string name;std::string email;// no operator==};void save(const Member& edited) {// std::find_if asks the lambda about each stored member and stops at// the first `true`: a match now means "same ID", whatever the details.const auto found = std::find_if(members_.begin(), members_.end(),[&](const Member& stored) { return stored.id == edited.id; });if (found != members_.end()) {*found = edited; // replace the old details with the edited ones} else {members_.push_back(edited); // a genuinely new member}}Better still, use the lesson’s
Member, with aMemberId, and store members in astd::unordered_map<MemberId, Member>, as in the example on this page: the key is the identity, and saving ismembers.insert_or_assign(edited.id(), edited). Removingoperator==also means that any other code relying on the wrong meaning stops compiling, which finds the rest of the bug.
Summary
Section titled “Summary”- “The same” can mean the same object in memory, equal values, or the same identity. Choose the one the domain needs.
- Value objects use value equality; in C++20,
= defaultonoperator==oroperator<=>writes it for you. - Entities are the same when their IDs are equal. Prefer named functions such as
same_memberto anoperator==whose meaning is unclear. - Give IDs their own types, with
explicitconstructors, so they cannot be mixed up; specializestd::hashto use them as keys, hashing exactly what==compares. - Never change the key of an element stored in a map or set.