C ++ confusing generic pointer

I found the code below in the section "C ++ Programming Language, Fourth Edition", chapter 17.5.1.3

struct S2 { shared_ptr<int> p; }; S2 x {new int{0}}; void f() { S2 y {x}; // ''copy'' x โˆ—yp = 1; // change y, affects x โˆ—xp = 2; // change x; affects y ypreset(new int{3}); // change y; affects x โˆ—xp = 4; // change x; affects y } 

I don't understand the last comment, indeed, yp should point to the new memory address after calling reset (), and therefore

  โˆ—xp = 4; 

should leave yp unchanged, right?

thanks

+8
c ++ pointers
source share
1 answer

The book is wrong and you are right. Perhaps you will send this to Bjarne so that it can be fixed in the next print. A.

Correct comments could be:

 S2 y {x}; // xp and yp point to the same int. *yp = 1; // changes the value of both *xp and *yp *xp = 2; // changes the value of both *xp and *yp ypreset(new int{3}); // xp and yp point to different ints. *xp = 4; // changes the value of only *xp 
+5
source share

All Articles