C++ shared_ptr's Non-Atomic Reference Counting: A Microbenchmark Surprise

2025-08-31
C++ shared_ptr's Non-Atomic Reference Counting: A Microbenchmark Surprise

A microbenchmark comparing Rust and C++ data structures revealed unexpected behavior in C++'s `shared_ptr`. In single-threaded environments, GNU libstdc++ optimizes `shared_ptr`'s reference counting to be non-atomic if `pthread_create` isn't imported. This performance optimization, while generally safe, can lead to issues in uncommon scenarios, such as when a dynamically linked library is loaded by a statically linked program. The author investigated other C++ implementations (libcxx and Visual C++) and ultimately resolved the performance discrepancy by referencing `pthread_create` in their benchmark. The discovery highlights the complexities of low-level optimizations and their potential unintended consequences.

Development