我在下面的"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
}
Run Code Online (Sandbox Code Playgroud)
我不明白最后的评论,确实yp应该在reset()调用后指向一个新的内存地址,等等
?x.p = 4;
Run Code Online (Sandbox Code Playgroud)
应该让yp不变,不是吗?
谢谢
这本书错了,你是对的.您可以考虑将其发送给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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |