Hasty Briefsbeta

Shared_ptr<T>: the (not always) atomic reference counted smart pointer

14 days ago
  • #shared_ptr
  • #C++
  • #optimization
  • shared_ptr<T> in GNU's libstdc++ optimizes reference counting by checking if pthread_create is imported, using atomic operations only if necessary.
  • The optimization was discovered during a micro-benchmark comparing Rust's Arc::clone with C++'s shared_ptr<T>, where C++ was unexpectedly faster due to non-atomic increments.
  • The safety of this optimization is generally sound but could break in rare cases like statically compiled binaries loading shared libraries without pthread symbols.
  • Other C++ implementations like libcxx and VisualC++ handle atomic operations differently, with libcxx allowing compile-time thread disabling.
  • Rust's Arc cannot adopt this optimization as it explicitly guarantees atomic operations, differentiating it from Rc which is non-atomic.