智能指针,为什么在改变底层对象之前需要检查我是否是唯一的用户? [英] Smart pointer, why need to check if I am the only user before changing the underlying object?

查看:143
本文介绍了智能指针,为什么在改变底层对象之前需要检查我是否是唯一的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 C++ Primer 并发现这些内容有点令人困惑:

<块引用>

reset 成员通常与 unique 一起使用来控制更改到多个 shared_ptr 之间共享的对象.更改之前底层对象,我们检查我们是否是唯一的用户.如果没有,我们在进行更改之前制作一个新副本:

if (!p.unique())p.reset(新字符串(*p));//我们并不孤单;分配一个新副本*p += newVal;//现在我们知道我们是唯一的指针,可以改变这个对象

上面引用的文字中强调的文字是什么意思?好纠结.

更新:

再读一遍课文,我发现我可能会漏掉一些东西.

所以根据上面的代码,我们假设有2 shared_ptr(这里提到的一个是p)指向原来的动态内存对象假设 A.然后如果我想修改对象A,我用A(new string(*p))的copy值分配一个新的动态内存,将其分配给 p,假设为 B.所以最终A没有被修改,而是只创建A的修改版本的副本?

为什么不直接做*p += newVal;?为什么它与答案中提到的 Copy-on-write 相关?我的意思是,不需要额外的复制操作.所有的shared_ptr 最初都指向动态内存对象A.只有 1 个对象.

<小时>

可能提供更多上下文的屏幕截图:

解决方案

因为你只能修改 shared_ptr 而不是它们引用的对象.这是为了防止数据竞争.

来自 util.smartptr.shared/4:

<块引用>

为了确定是否存在数据竞争,成员函数应访问和修改shared_ptrweak_ptr对象本身和不是它们所引用的对象.

变化use_count() 不反映可以引入数据的修改比赛.

对于reset() 成员函数:

<块引用>

void reset() noexcept;

效果:相当于shared_ptr().swap(*this).

I am reading C++ Primer and find these kinda confusing:

The reset member is often used together with unique to control changes to the object shared among several shared_ptrs. Before changing the underlying object, we check whether we’re the only user. If not, we make a new copy before making the change:

if (!p.unique())
    p.reset(new string(*p)); // we aren't alone; allocate a new copy
*p += newVal; // now that we know we're the only pointer, okay to change this object

What does the emphasized text mean in the quoted text above? So confused.

Update:

After reading the text again, I find out that I may miss something.

So according the code above, let's assume there are 2 shared_ptr (one is p mentioned here) pointing to the original dynamic memory object let's say A. Then if I want to modify object A, I allocate a new dynamic memory with the copy value of A(new string(*p)), assign it to p, let's say B. So eventually A is not modified, but only create a copy of modified version of A?

Why not directly do *p += newVal;? And why is it related to Copy-on-write mentioned in answers? I mean, there's no extra copy operation needed. All shared_ptr originally points to dynamic memory object A. Only 1 object.


Screenshot that may supply a little bit more context:

解决方案

For you are only allowed to modify the shared_ptr and not the objects they refer to. This is to prevent data races.

From util.smartptr.shared/4:

For purposes of determining the presence of a data race, member functions shall access and modify only the shared_­ptr and weak_­ptr objects themselves and not objects they refer to.

Changes in use_­count() do not reflect modifications that can introduce data races.

For the reset() member function:

void reset() noexcept;

Effects: Equivalent to shared_­ptr().swap(*this).

这篇关于智能指针,为什么在改变底层对象之前需要检查我是否是唯一的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆