ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

理解c共享指针

2019-08-24 05:07:41  阅读:265  来源: 互联网

标签:c shared-ptr pointers smart-pointers


嗨我正在制作我自己的引用计数智能指针,但在我开始之前有两个概念我不太明白.

>当我创建一个共享指针指向一个对象时,我必须为一个结构/类分配内存,该结构/类将包含诸如引用计数(最初为一个)之类的信息,也可能是一个互斥量以及递增和递减.当我使用时,假设=运算符使另一个共享指针也指向该对象,我也将指向此结构/类的指针传递给该新指针,这样我就可以增加计数.我的问题是,如果我使第三个共享指针指向此对象(不使用复制构造函数或=运算符),那么此指针将不知道结构,因此将引用计数为1,如果我然后删除指针,计数将达到0并且对象将被销毁,实际上,此对象还有另外两个指针?
>如果共享指针的引用计数为1,然后创建多个线程,如果一个线程结束/销毁它,那么可能仍在运行的其他线程会发生什么?

解决方法:

I get that when a shared pointer is created to point to an object I must allocate memory for a struct/class that will contain information such as the reference count (initially one) and maybe a mutex as well for incrementing and decrementing.

是的,你需要一个柜台.
只有在计划多线程时才需要互斥锁.我会集中精力让计数工作首先担心锁定后记.

When I use, say the =operator to make another shared pointer also point to this object, I will also pass the pointer to this struct/class to that new pointer so I can increment the count.

关于共享指针的观点是它们取得了指针的所有权.一旦创建了共享指针,就不应该有指向同一对象的RAW指针的实例.因此,当您复制或分配时,您正在通过共享指针执行所有操作.

My question is, if I make a third shared pointer point to this object(not using the copy constructor or =operator), then this pointer won’t know about the struct and therefore will have a reference count of 1.

你的假设是正确的.这就是为什么当你创建共享指针时,你不应该保留指针的副本.这是引入std :: make_shared()的另一个原因,它分配内存并立即将其包装在智能指针中,因此没有RAW指针返回给用户代码.

if I then delete the pointer, the count will reach 0 and the object will be destroyed when in fact, there are two other pointers for this object?

这正是问题所在.这就是为什么你不应该创建或传递RAW指针到已经被管理的对象.

If a shared pointer has a reference count of 1, and then multiple threads are created, if one thread ends/destroys it, what happens with the other threads that may still be running?

如果您的引用计数有效并且您只有管理RAW指针的共享指针,它应该按预期工作.但如果你在一个线程中删除它,它将在所有线程中被销毁.

标签:c,shared-ptr,pointers,smart-pointers
来源: https://codeday.me/bug/20190824/1704797.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有