【问题标题】:C++ entangled shared pointerC++纠缠共享指针
【发布时间】:2015-02-10 13:11:57
【问题描述】:

我在“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 不变,不是吗?

谢谢

【问题讨论】:

标签: c++ pointers


【解决方案1】:

这本书是错的,你是对的。您可以考虑将其发送给 Bjarne,以便在下次印刷时修复。

正确的 cmets 可能是:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-11
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多