C++;纠缠共享指针 我在《C++程序设计语言,第四版》第175.1.3/P>中找到了下面的代码 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 }
应该让y.p.保持不变,不是吗C++;纠缠共享指针 我在《C++程序设计语言,第四版》第175.1.3/P>中找到了下面的代码 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 },c++,pointers,C++,Pointers,应该让y.p.保持不变,不是吗 谢谢这本书是错的,你是对的。您可以考虑将此发送到BJARNE,以便可以在下一次打印中固定。 正确的评论可能是: 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 o
谢谢这本书是错的,你是对的。您可以考虑将此发送到BJARNE,以便可以在下一次打印中固定。 正确的评论可能是:
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
clang似乎不同意这是一本大书,肯定会有错误的例子,见我最近的Bjarne所说的,请随意给我推荐勘误表。我将在本书的约束范围内纠正所有可以纠正的错误。如何联系他可以在网上找到。
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