splobjectstorage

SplObjectStorage implements Countable, SeekableIterator, Serializable, ArrayAccess

A storage keyed by object identity: one slot per object; attach/contains/detach (deprecated since 8.5 — prefer the offset* API) can also carry associated data, serving as both an object set and an object-to-data map: the container form of identity-vs-equality (see spl_object_id).

C C23

C23
#include <stdio.h>

#define CAP 8
static const void *keys[CAP];
static const char *vals[CAP];
static int n = 0;

static int index_of(const void *p) { /* linear search by identity */
    for (int i = 0; i < n; i++) if (keys[i] == p) return i;
    return -1;
}
static void attach(const void *p, const char *v) {
    int i = index_of(p);
    if (i < 0) { keys[n] = p; vals[n] = v; n++; }
    else vals[i] = v;
}
static int contains(const void *p) { return index_of(p) >= 0; }
static void detach(const void *p) { /* swap-remove keeps it O(1) */
    int i = index_of(p);
    if (i >= 0) { keys[i] = keys[n - 1]; vals[i] = vals[n - 1]; n--; }
}

int main(void) {
    char a[16] = "a";
    char b[16] = "b";
    char c[16] = "a"; /* same content, different object */
    attach(a, "alpha");
    attach(b, NULL);
    printf("%d\n", n);           /* 2 */
    printf("%d\n", contains(a)); /* the same object */
    printf("%d\n", contains(c)); /* equal content, different identity */
    detach(a);
    printf("%d\n", n);           /* 1 */
    printf("%d\n", contains(a)); /* gone */
    printf("%d\n", contains(b)); /* the other object stays */
    return 0;
}
Output
2
1
0
1
0
1

C++ C++26

C++26
#include <iostream>
#include <string>
#include <unordered_map>

int main() {
    std::unordered_map<const void *, std::string> bag; // keys are identities (addresses)
    auto a = new std::string("a");
    auto b = new std::string("b");
    bag[a] = "alpha";
    bag[b] = "";
    std::cout << bag.size() << "\n";                  // 2
    std::cout << bag.count(a) << "\n";                // the same object
    std::cout << bag.count(new std::string("a")) << "\n"; // a fresh object: different key
    bag.erase(a);                                     // detach
    std::cout << bag.size() << "\n";                  // 1
    std::cout << bag.count(a) << "\n";                // gone
    std::cout << "\"" << bag[b] << "\"\n";            // data of b
    delete a;
    delete b;
    return 0;
}
Output
2
1
0
1
0
""

C# v11.0.100

v11.0.100
using System;
using System.Collections.Generic;

var bag = new Dictionary<object, string?>(ReferenceEqualityComparer.Instance);
var a = new object();
var b = new object();
bag[a] = "alpha";
bag[b] = null;
Console.WriteLine(bag.Count);            // 2
Console.WriteLine(bag.ContainsKey(a));   // the same object
Console.WriteLine(bag.ContainsKey(new object())); // a fresh object: different key
bag.Remove(a);                           // detach
Console.WriteLine(bag.Count);            // 1
Console.WriteLine(bag.ContainsKey(a));   // gone
Console.WriteLine(bag[b] == null ? "null" : bag[b]); // data of b
Output
2
True
False
1
False
null

Go v1.27.4

v1.27.4
package main

import "fmt"

type node struct{ name string }

func main() {
	bag := make(map[*node]string) // pointer keys: identity is the address
	a := &node{"a"}
	b := &node{"b"}
	bag[a] = "alpha"
	bag[b] = ""
	fmt.Println(len(bag))            // 2
	_, ok := bag[a]
	fmt.Println(ok)                  // the same object
	_, ok = bag[&node{"a"}]
	fmt.Println(ok)                  // a fresh object is a different key
	delete(bag, a)                   // detach
	fmt.Println(len(bag))            // 1
	_, ok = bag[a]
	fmt.Println(ok)                  // gone
	fmt.Printf("%q\n", bag[b])       // data of b
}
Output
2
true
false
1
false
""

Java v27.0.1

v27.0.1
import java.util.IdentityHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<Object, String> bag = new IdentityHashMap<>(); // keys compare by identity (==)
        Object a = new Object();
        Object b = new Object();
        bag.put(a, "alpha");
        bag.put(b, null);
        System.out.println(bag.size());                    // 2
        System.out.println(bag.containsKey(a));            // the same object
        System.out.println(bag.containsKey(new Object())); // a fresh object: different key
        bag.remove(a);                                     // detach
        System.out.println(bag.size());                    // 1
        System.out.println(bag.containsKey(a));            // gone
        System.out.println(bag.get(b));                    // null data
    }
}
Output
2
true
false
1
false
null

JavaScript v26.13.1

v26.13.1
// Map keys compare by identity (SameValueZero): an object is its own key
const bag = new Map();
const a = { name: "a" };
const b = { name: "b" };
bag.set(a, "alpha");
bag.set(b, null);
console.log(bag.size);                 // 2
console.log(bag.has(a));               // the same object
console.log(bag.has({ name: "a" }));   // a fresh object is a different key
bag.delete(a);                         // detach
console.log(bag.size);                 // 1
console.log(bag.has(a));               // gone
console.log(bag.get(b));               // null
Output
2
true
false
1
false
null

PHP v8.6.0

v8.6.0
$bag = new SplObjectStorage();
$a = new stdClass();
$b = new stdClass();
$bag[$a] = "alpha";            // attach $a and associate data
$bag[$b] = null;               // attach $b
var_dump(count($bag));         // 2
var_dump(isset($bag[$a]));     // identity lookup: same object
var_dump(isset($bag[new stdClass()])); // a fresh object is a different key
unset($bag[$a]);               // detach
var_dump(count($bag));         // 1
var_dump(isset($bag[$a]));     // gone
var_dump($bag[$b]);            // null data
Output
int(2)
bool(true)
bool(false)
int(1)
bool(false)
NULL

Python v3.15.2

v3.15.2
# default object.__hash__ is derived from id(): an identity-keyed dict
bag = {}
a = object()
b = object()
bag[a] = "alpha"
bag[b] = None
print(len(bag))          # 2
print(a in bag)          # the same object
print(object() in bag)   # a fresh object is a different key
del bag[a]               # detach
print(len(bag))          # 1
print(a in bag)          # gone
print(bag[b])            # None
Output
2
True
False
1
False
None

Rust v1.99.1

v1.99.1
use std::collections::HashMap;

fn main() {
    // no runtime object id: key the map by the object's address
    let a = Box::new(String::from("a"));
    let b = Box::new(String::from("b"));
    let mut bag: HashMap<usize, String> = HashMap::new();
    bag.insert(&*a as *const String as usize, String::from("alpha"));
    bag.insert(&*b as *const String as usize, String::new());
    let key_of = |p: &String| p as *const String as usize;
    println!("{}", bag.len());                     // 2
    println!("{}", bag.contains_key(&key_of(&a))); // the same object
    let c = Box::new(String::from("a"));
    println!("{}", bag.contains_key(&key_of(&c))); // a fresh object: different key
    bag.remove(&key_of(&a));                       // detach
    println!("{}", bag.len());                     // 1
    println!("{}", bag.contains_key(&key_of(&a))); // gone
    println!("{:?}", bag.get(&key_of(&b)));        // data of b
}
Output
2
true
false
1
false
Some("")

TypeScript v26.13.1

v26.13.1
// Map keys compare by identity: an object is its own key
const bag = new Map<object, string | null>();
const a: object = { name: "a" };
const b: object = { name: "b" };
bag.set(a, "alpha");
bag.set(b, null);
console.log(bag.size);               // 2
console.log(bag.has(a));             // the same object
console.log(bag.has({ name: "a" })); // a fresh object is a different key
bag.delete(a);                       // detach
console.log(bag.size);               // 1
console.log(bag.has(a));             // gone
console.log(bag.get(b));             // null
Output
2
true
false
1
false
null

Language differences

C: no objects and no container library — hand-roll a pointer array with linear search for attach/contains/detach; the example uses swap-remove to stay O(1), pointer equality for identity, and treats equal content at a different address as a different key.

C++: unordered_map<const void *, V> keyed by address is an object set; note the demo deletes what it new'ed, and the raw-pointer key dangles once the pointee is destroyed.

C#: Dictionary<object, V> + ReferenceEqualityComparer.Instance (.NET 5+) gives reference-identity keys; without it, default Equals is value comparison and two equal objects would collide.

Go: map[*T]V natively keys by pointer identity; &node{"a"} evaluates to a fresh object each time — a temporarily constructed address must not be used as a long-lived key.

Java: IdentityHashMap is the native counterpart — keys compare with == (identity) instead of equals; the key type is written as Object because the class deliberately bypasses equals semantics.

JavaScript: Map keys compare with SameValueZero, so object keys are reference identity; use Map when you need size/iteration — WeakMap has no size and is not iterable, but its weak keys suit object-to-metadata maps without leaks.

PHP: SplObjectStorage keys by object identity (internally a handle hash, visible via getHash()): $bag[$obj] = $data attaches and associates data at once, isset($bag[$obj]) is contains, unset($bag[$obj]) is detach; re-adding the same object occupies one slot. Note attach()/contains()/detach() are deprecated since 8.5 (the manual points to the offset* family), so the example uses the new API. foreach yields the objects themselves (associated data is read via $bag[$obj]); incidentally, in foreach ($s as $k => $obj) the $k is a serial number, not the object — a well-known quirk from the manual's user notes. Cross-link spl_object_id: an identity-keyed container is object ids in disguise.

Python: use objects directly as dict keys — the default object.__hash__ derives from id(), which is exactly identity semantics; a custom class overriding __eq__ must also define __hash__, or it becomes unhashable or drifts semantically.

Rust: no runtime object id and no built-in weak-ref container — the demo keys a HashMap by the Box's address cast as usize; address reuse is the hazard: once the object is dropped the address may be recycled, so a long-lived address key must keep the object alive (fine for a demo, not for production).

TypeScript: same runtime as JS — Map<object, V> is the object set; the object key type signals "the key is a reference".