std::shared_ptr 中的计数器是原子的吗?

Is counter in std::shared_ptr atomic?

在面试中,我被问到 std::shared_ptr 中计数器的特殊性是什么(它是一个原子)。但是,我听说 std::shared_ptr 不能很好地处理多线程。什么是真的?

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.

换句话说,您可以安全地构造和复制它们,但共享对象本身不受保护。