Sam Mokari
Sam Mokari

Reputation: 471

Are smart pointers thread safe?

A smart pointer is an abstract data type that simulates a pointer while providing added features such as automatic memory management or bounds checking.

My question is, are they thread-safe?

Upvotes: 1

Views: 4409

Answers (1)

David Schwartz
David Schwartz

Reputation: 182799

Various different smart pointer objects provide various different degrees of thread safety. You have to check the documentation for the individual implementation carefully to see what level of thread safety it provides.

The most common question is specifically about std::shared_ptr and std::weak_ptr. These provide standard thread safety for individual pointer instances. That is, one thread must not access a shared_ptr or weak_ptr while another thread is, or might be, modifying that exact same shared_ptr or weak_ptr object. However, they provide full thread safety for distinct pointers that reference the same object. So one thread can modify a shared_ptr while another thread is accessing a shared_ptr to that same underlying object whose lifetime is managed by the smart pointers.

Upvotes: 4

Related Questions