C++纠缠在一起的共享指针
C++ entangled shared pointer
我在"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
相关文章:
- 如何从具有移动语义的类对象中生成共享指针
- 使用共享指针的函数调用,其对象应为 const
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何访问由共享指针保存的类方法?
- 从矢量或地图中删除共享指针
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 使用共享指针实现复制 c'tor?
- 共享指针继承,而不先显式强制转换
- 如何检查类中共享指针的有效性?
- std::排序在共享指针的向量上
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 嵌套类、继承和C++中的共享指针
- 制作一对共享指针并推送一个向量
- 如何将共享指针用作函数参数
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 尝试通过共享指针使用变量时读取访问冲突
- 如何将元素插入到标准::地图的共享指针中?
- 共享指针生存期
- 初始化可变数据结构中的共享指针向量
- 阻止在返回时复制共享指针