C++纠缠在一起的共享指针

C++ entangled shared pointer

本文关键字:共享 指针 在一起 纠缠 C++      更新时间:2023-10-16

我在"C++编程语言,第 4 版"第 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
}

我不明白最后一条评论,确实y.p应该在reset()调用后指向一个新的内存地址,等等

    ∗x.p = 4; 

应该让 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 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