I have found code below in "The C++ programming language, 4th edition", chapter 17.5.1.3
struct S2 {
shared_ptr<int> p;
};
S2 x {new int{0}};
void f()
{
S2 y {x}; // ‘‘copy’’ x
∗y.p = 1; // change y, affects x
∗x.p = 2; // change x; affects y
y.p.reset(new int{3}); // change y; affects x
∗x.p = 4; // change x; affects y
}
I don't understand the last comment, indeed y.p should point to a new memory address after the reset() call, and so
∗x.p = 4;
should let y.p unchanged, isn't it?
Thanks
The book is wrong and you are correct. You might consider sending this to Bjarne so it could be fixed in the next printing.
The correct comments might be:
S2 y {x}; // x.p and y.p point to the same int.
*y.p = 1; // changes the value of both *x.p and *y.p
*x.p = 2; // changes the value of both *x.p and *y.p
y.p.reset(new int{3}); // x.p and y.p point to different ints.
*x.p = 4; // changes the value of only *x.p
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