I am reading C++ Primer and find these kinda confusing:
resetmember is often used together with
uniqueto control changes to the object shared among several
shared_ptrs. Before changing the underlying object, we check whether we’re the only user. If not, we make a new copy before making the change:
if (!p.unique()) p.reset(new string(*p)); // we aren't alone; allocate a new copy *p += newVal; // now that we know we're the only pointer, okay to change this object
What does the emphasized text mean in the quoted text above? So confused.
After reading the text again, I find out that I may miss something.
So according the code above, let's assume there are
shared_ptr (one is
p mentioned here) pointing to the original dynamic memory object let's say
A. Then if I want to modify object
A, I allocate a new dynamic memory with the copy value of
new string(*p)), assign it to
p, let's say
B. So eventually
A is not modified, but only create a copy of modified version of
Why not directly do
*p += newVal;? And why is it related to Copy-on-write mentioned in answers? I mean, there's no extra copy operation needed. All
shared_ptr originally points to dynamic memory object
A. Only 1 object.
For you are only allowed to modify the
shared_ptr and not the objects they refer to. This is to prevent data races.
For purposes of determining the presence of a data race, member functions shall access and modify only the
weak_ptrobjects themselves and not objects they refer to.
use_count()do not reflect modifications that can introduce data races.
reset() member function:
void reset() noexcept;
Effects: Equivalent to