October 25, 2026

std::map::operator[] Can Change the Map You Are Reading

A lookup should not silently change configuration. Yet that is exactly what std::map::operator[] does when the key is missing.

Imagine a daemon reading retry limits from a map. It receives a service name that was not configured. The lookup returns zero, the code continues, and now the configuration map contains a new entry that no configuration file ever defined. Nothing crashes. The failure may not become visible until a later diagnostic decides that the service was configured explicitly.

This is not a bug in std::map. It is a mismatch between the operation we intended—read an existing value—and the API we called—return an existing value or create one. The distinction affects error handling, resource use, multithreading, and the guarantees an API can make to its callers.

Scope

Examples use C++17 and C++20 features where indicated. The focus is ordered std::map, not a general comparison of every associative container. Some of the same lookup-versus-insertion traps exist in std::unordered_map, but iterator invalidation and performance details differ.

std map operator 1

The read that creates a new entry


Consider a small retry-budget registry. A service is configured with three attempts; another service is not configured at all:

#include <iostream>
#include <map>
#include <string>

int main()
{
    std::map<std::string, unsigned> retryBudget{
        {"telemetry", 3}
    };

    const auto before = retryBudget.size();
    const auto limit = retryBudget["diagnostics"];

    std::cout << "limit=" << limit << '\n';
    std::cout << "before=" << before
              << " after=" << retryBudget.size() << '\n';
}

The output is:

limit=0
before=1 after=2

"diagnostics" was absent. Accessing it with [] inserted an entry with a value-initialized unsigned, which is zero. The returned value looked ordinary, but the collection changed underneath the code doing the read.

In a unit test this is obvious. In a process that runs for months, accepts service names over IPC, and uses the same map for both lookups and diagnostics, it is much harder to see.

What operator[] actually promises


For a missing key, std::map::operator[] inserts a new element and returns a reference to its mapped value. Since C++17, the operation is specified in terms of try_emplace(key).first->second. With the usual allocator, the new mapped value is value-initialized.

  • std::map<Key, int>: the new integer is 0.
  • std::map<Key, std::string>: the new string is empty.
  • std::map<Key, std::unique_ptr<T>>: the new pointer is null.
  • std::map<Key, std::function<void()>>: the new function wrapper is empty.

The operation needs a usable way to construct the mapped value without arguments. With ordinary standard allocators, this means the mapped type must be default-constructible. That requirement applies to a call of [] even when we are convinced the key already exists at runtime.

It is also not a cheap, read-only operation on a miss. Insertion may allocate a tree node, copy or move the key, construct the mapped value, and rebalance the tree. Lookup and insertion have logarithmic complexity; the hidden allocations and construction work are additional costs.

One subtle detail: inserting into std::map does not invalidate existing iterators or references. That is useful, but it can make unintended mutation less obvious: the program keeps running with valid references and a new, semantically invalid entry.

Not a const operation

There is no const overload of std::map::operator[]. A read-only reference to a map cannot use it, precisely because a missing key could modify the container.

std map operator 2

Failure mode: a missing policy becomes a configured policy


A more realistic example is a middleware daemon with service-specific retry policies:

#include <chrono>
#include <map>
#include <string>

struct RetryPolicy {
    unsigned maxAttempts = 0;
    std::chrono::milliseconds backoff{0};
};

using Policies = std::map<std::string, RetryPolicy>;

bool shouldRetry(Policies& policies, const std::string& service)
{
    return policies[service].maxAttempts > 0;
}

Suppose the configuration contains telemetry and ota, while a request arrives for diagnostics. shouldRetry() returns false; that may seem like safe default behavior. But it also adds "diagnostics" to the map with maxAttempts == 0 and backoff == 0ms.

The next stage may enumerate the map to report configured services, export it over D-Bus, serialize it for an on-device diagnostic, or merge it into a later configuration update. The new entry now looks indistinguishable from a deliberate zero-retry policy unless the system records the distinction elsewhere.

The production question is not whether zero is a reasonable default. It is whether an unknown service is a valid absence, an invalid request, or an instruction to create new state. Those are three different contracts.

A dangerous hidden assumption

If the caller is reading configuration, an unknown key should not silently turn into configuration. When a missing key is a normal event, return an explicit absence. When it violates an invariant, report an error. When creation is intended, make insertion visible.

std map operator 3

Use find() when absence is part of normal operation


If a lookup is allowed to miss, find() communicates that intent. It returns an iterator to the entry or end() when the key is absent. No new entry is created.

const auto it = policies.find(service);
if (it == policies.end()) {
    reportUnknownService(service);
    return;
}

scheduleRetry(it->second);

This is usually the right shape for message routing, per-device configuration, registered callbacks, protocol IDs, caches, and other registries where “not present” is an expected branch. Notice that the caller can distinguish a missing policy from a valid policy with maxAttempts == 0.

A useful API improvement is to expose the registry as read-only to consumers, so accidental insertion is rejected at compile time:

#include <functional>
#include <map>
#include <string>
#include <string_view>

using Policies =
    std::map<std::string, RetryPolicy, std::less<>>;

const RetryPolicy* findPolicy(
    const Policies& policies,
    std::string_view service)
{
    const auto it = policies.find(service);
    return it == policies.end() ? nullptr : &it->second;
}

std::less<> makes comparison transparent. In C++17 and later, this permits a std::string_view lookup without constructing a temporary std::string just for the search. The returned pointer is non-owning: it remains valid only while that element still exists and the map outlives its use. In a registry with concurrent updates, a pointer must not outlive the relevant synchronization.

If you only need membership, contains() (C++20) reads more clearly:

if (!policies.contains(service)) {
    reportUnknownService(service);
}

But do not turn contains() into an extra lookup before fetching the value. If the value is needed, find() already answers both questions with one search. And contains() followed by [] still uses an inserting API.

Use at() when a missing key means the program is wrong


Sometimes the key must exist. For example, the set of built-in service roles may be validated at startup, and a later code path refers only to these validated role IDs. In that case, at() makes the expectation visible:

const auto& policy = policies.at("telemetry");
startWorker(policy);

The important difference is the failure behavior. On a missing key, at() throws std::out_of_range instead of adding a default entry. It also has a const overload. This can be a useful last-line defense against broken invariants.

But at() is not a replacement for input validation. If arbitrary service names arrive from a socket, unknown names are normal input errors; do not use exceptions as your routine routing protocol. On embedded targets built without C++ exception support, select an explicit lookup-and-error path rather than relying on at() to signal absence.

Practical distinction

Use find() when “not found” is a legitimate result that the caller handles. Use at() when the key should already exist and a miss indicates a violated invariant. Neither silently creates state.

Use try_emplace() when creating an entry is the operation


When the code really intends to create per-service state on first use, do not hide that decision inside a supposed read. try_emplace() states it explicitly and tells you whether insertion occurred.

#include <chrono>
#include <map>
#include <string>

using namespace std::chrono_literals;

struct RetryState {
    RetryState(std::chrono::milliseconds delay,
               unsigned maxAttempts)
        : delay(delay), maxAttempts(maxAttempts) {}

    std::chrono::milliseconds delay;
    unsigned maxAttempts;
};

std::map<std::string, RetryState> states;

auto [it, inserted] =
    states.try_emplace("telemetry", 250ms, 3u);

if (inserted) {
    recordNewServiceState(it->first);
}

useState(it->second);

Unlike [], this works with a mapped type that has no default constructor. The RetryState is constructed from the supplied arguments only when insertion succeeds. The returned bool makes first-use creation observable, which is useful for metrics, initialization, and duplicate-registration handling.

try_emplace() also avoids moving from forwarded mapped-value arguments when the key already exists. That matters when the mapped value is move-only. However, the expressions passed as arguments are still evaluated before the function call:

// Expensive factory runs even when "telemetry" is already present.
auto [it, inserted] = states.try_emplace(
    "telemetry", loadBackoffFromStorage(), 3u);

To defer an expensive factory call until a key is known to be absent, perform the check explicitly and accept the extra lookup on the miss (or choose a different construction strategy):

auto it = states.find(service);
if (it == states.end()) {
    it = states.try_emplace(
        service, loadBackoffFromStorage(), 3u).first;
}

useState(it->second);

This pattern assumes the lookup and insertion are performed in a single-threaded context or under one suitable lock. A separate check does not make concurrent insertion safe by itself.

Do not confuse try_emplace with overwrite

try_emplace() leaves an existing value unchanged. If a configuration reload must replace an existing value or insert a new one, insert_or_assign() (C++17) expresses that different operation. Both modify the map on insertion; only the latter also assigns on a hit.

std map operator 4

Which API matches the contract?


OperationMissing keyExisting keyUse it when
map[key]Inserts value-initialized TReturns mutable T&Creation with a default value is intended
map.find(key)Returns end()Returns iterator to entryAbsence is a normal outcome; need the value
map.at(key)Throws std::out_of_rangeReturns mapped referenceA miss violates the caller’s invariant
map.contains(key) (C++20)Returns falseReturns trueNeed membership only
map.try_emplace(key, args...) (C++17)Constructs and inserts TLeaves mapped value unchangedFirst-use creation with explicit constructor arguments
map.insert_or_assign(key, value) (C++17)Inserts a valueAssigns a replacement valueCreate-or-update configuration or registries

These operations all look compact at a call site. They do not say the same thing. Picking the correct one is primarily an API-contract decision; performance is the second-order consideration.

When operator[] is exactly the right tool


There is no reason to ban []. A counter map is a good example of intentional default insertion:

std::map<std::string, std::size_t> droppedPackets;

void recordDrop(const std::string& reason)
{
    ++droppedPackets[reason];
}

The desired meaning is: “if this reason has never appeared, start its counter at zero, then increment it.” In this case, default insertion is part of the algorithm.

But make sure the key space is controlled. If reason comes directly from untrusted packet fields, the same convenient counter can grow one tree node per distinct attacker-controlled string. In production, map incoming values into a finite set of known categories or enforce a bounded-cardinality policy before updating metrics.

Another valid use is an explicitly mutable cache or accumulator, provided the cost of a default value is acceptable. The question is always the same: would a missing key legitimately create a new entry here? If not, choose another API.

Concurrency turns a harmless-looking lookup into a data race


The dangerous version of the problem appears when a shared registry is read from multiple worker threads. A developer may treat policies[service] as a read because the key “should already exist.” The function remains an insertion-capable non-const operation, and a miss can mutate the tree while another thread is traversing or reading it.

// WRONG when multiple threads can access this map concurrently.
std::map<std::string, unsigned> retryBudget;

unsigned getBudget(const std::string& service)
{
    return retryBudget[service]; // may insert and race
}

The standard library permits concurrent const access to the same container, subject to the usual rules about the objects being accessed. For associative containers, operator[] is not among the operations treated as const for these thread-safety guarantees. The fact that std::map insertion preserves iterators does not make concurrent insertion and lookup safe.

A production registry needs an ownership model. One option is to build an immutable map and publish it to readers; another is to protect both reads and updates with appropriate synchronization. If you use a shared mutex and return a value that survives unlocking, copy the policy while holding the read lock:

#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string>
#include <string_view>

class PolicyRegistry {
public:
    std::optional<RetryPolicy> get(std::string_view service) const
    {
        std::shared_lock lock{mutex_};
        const auto it = policies_.find(service);
        if (it == policies_.end()) {
            return std::nullopt;
        }
        return it->second; // copy while locked
    }

    void update(std::string name, RetryPolicy policy)
    {
        std::unique_lock lock{mutex_};
        policies_.insert_or_assign(std::move(name), std::move(policy));
    }

private:
    mutable std::shared_mutex mutex_;
    Policies policies_;
};

Here Policies is the transparent-comparator alias defined earlier. get() makes missing configuration explicit and does not expose a pointer into mutable shared state after the lock is released. This is reasonable for a small policy object; for expensive-to-copy values or very high read rates, use a different publication or lifetime strategy.

Iterator stability is not thread safety

Even though inserting into std::map leaves existing iterators valid, unsynchronized reads overlapping with writes can still have undefined behavior. A find() call does not make concurrent writes safe unless access to the registry is coordinated.

functionpointers

How to catch accidental insertion during debugging


Sanitizers are useful, but a single-threaded accidental insertion is legal C++. AddressSanitizer and UndefinedBehaviorSanitizer will not complain merely because a lookup expanded a map. Find it with invariant checks and observability instead.

  • Make readers take const Policies&. This is the cheapest compile-time guard against accidental use of [] in read-only code.
  • Assert registry size and membership in tests. A lookup for an unknown key should leave both the count and the key set unchanged.
  • Record legitimate creations at one explicit insertion point. The inserted flag returned by try_emplace() can feed a bounded, low-cardinality counter or diagnostic.
  • Inspect unexpected growth. If a configuration registry should contain 12 known services but grows after processing requests, log the source of the new keys and the call path that inserted them.
  • Use ThreadSanitizer for real concurrency reproductions. It can expose concurrent access problems; it does not decide whether creating a key was semantically correct.

A tiny regression test captures the expected behavior:

const auto before = policies.size();
const auto* unknown = findPolicy(policies, "unknown-service");

assert(unknown == nullptr);
assert(policies.size() == before);
assert(!policies.contains("unknown-service"));

For a reproducible local demonstration, save the complete main() from the first example as map_lookup.cpp and build it with:

c++ -std=c++20 -O0 -g -Wall -Wextra -Wpedantic \
    map_lookup.cpp -o map_lookup
./map_lookup

The deterministic size change proves the semantic problem. You do not need a profiler, a sanitizer, or a sophisticated debugger to see it. For a concurrent reproduction, instrument the actual multi-threaded component and build it separately with -fsanitize=thread; do not mistake an unreported logical insertion for proof that the design is safe.

Production rules worth enforcing in code review


  • Read-only configuration: expose it through const&, an immutable snapshot, or an API that cannot insert.
  • Expected absence: use find(), contains(), or an explicit optional result; keep missing distinct from a mapped default value.
  • Broken invariant: use at() when an exception is an appropriate failure signal; otherwise return an explicit error from a checked lookup.
  • First-use construction: use try_emplace() and observe whether insertion happened. Avoid unnecessary expensive argument evaluation.
  • Refresh or overwrite: use insert_or_assign() when existing values should be replaced.
  • Counter maps: ++counts[key] is valid when default-zero means what the algorithm needs; bound the key space.
  • Shared maps: define locking or snapshot ownership before introducing concurrent readers; iterator stability does not remove the need for synchronization.

The useful code-review question is not “is [] allowed here?” It is “is inserting a new entry an acceptable consequence of this expression?” If the answer is no, it is the wrong lookup API.

Conclusion


std::map::operator[] is an access-and-create operation. It is convenient and sometimes exactly correct, but it is not a harmless read. In production code, keep observation, invariant checking, and mutation separate: find() for optional presence, at() for required presence, and try_emplace() for deliberate first-use creation. The difference is only a few characters at the call site; the difference in system behavior can be substantial.

Reference documentation


For the precise library contracts, see the C++ reference entries for std::map::operator[], std::map::try_emplace, and standard container thread-safety rules.