At the interview, I was asked what is the peculiarity of the counter in std::shared_ptr(it is an atomic). However, I have heard opinions that std::shared_ptr doesn't work well with multithreading. What is true?
All member functions (including copy constructor and copy assignment) can be called by multiple threads on different instances of shared_ptr without additional synchronization even if these instances are copies and share ownership of the same object. If multiple threads of execution access the same shared_ptr without synchronization and any of those accesses uses a non-const member function of shared_ptr then a data race will occur; the shared_ptr overloads of atomic functions can be used to prevent the data race.
In other words, you can construct and copy them safely but the shared object itself is not protected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With