Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ entangled shared pointer

Tags:

c++

pointers

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

like image 644
Fabrice Jammes Avatar asked Dec 11 '14 22:12

Fabrice Jammes


1 Answers

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
like image 58
Bill Lynch Avatar answered Nov 16 '22 23:11

Bill Lynch