What is the technical problem with std::shared_ptr::unique()
that is the reason for its deprecation in C++17?
According to cppreference.com, std::shar
Consider the following code:
// global variable
std::shared_ptr s = std::make_shared();
// thread 1
if (s && s.unique()) {
// modify *s
}
// thread 2
auto s2 = s;
Here we have a classic race condition: s2
may (or may not) be created as a copy of s
in thread 2 while thread 1 is inside the if
.
The unique() == true
means that no one has a shared_ptr
pointing to the same memory, but does not mean any other threads have no access to initial shared_ptr
directly or through pointers or references.