C++管理共享对象的句柄问题
是否有管理由 2 个或更多其他对象共享的对象的最佳实践。即使在不同的线程上运行?
例如,创建 A 并将指向它的指针赋予 B 和 C。 ObjA A = new ObjA(); B->GiveObj(A); C->GiveObj(A);
现在我怎样才能删除objA?
到目前为止,我想到的是 A 监视它有多少个引用,当该计数器为 0 时,它会删除它(例如,当 A 被传递时,接收器调用 A->Aquire(),当它完成时,它调用 A ->release();
或者我可以告诉 B->RemoveObj(A); 和 C->RemoveObj(A); 问题是如果 B 或 C 在不同的线程上运行,我无法删除 A直到他们完成 A,并且他们看到了 RemoveObj 调用(这需要一堆混乱的标志),
是否有一个很好的方法来做到这一点,可能是使用 Signal/Slot
?
Is there best practice for managing Object shared by 2 or more others Object. Even when running on different thread?
For example A is created and a pointer to it is given to B and C.
ObjA A = new ObjA();
B->GiveObj(A);
C->GiveObj(A);
Now how can I delete objA?
So far what I though about is A monitor how many ref there are to it and when this counter is 0 it delete this (such as when A is passed, the receiver call A->Aquire(), when its done it call A->release();
Or I could tell B->RemoveObj(A); and C->RemoveObj(A); The problem with that is if B or C are running on a different thread, I cannot delete A until they are done with A, and they have seen The RemoveObj call. (Which require a bunch of messy flags).
Would there be a nice way to do this, possibly with Signal/Slot?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好的选择是使用智能指针实现,例如Boost的shared_ptr 。
这允许您根据需要传递指针,而不必担心删除。
编辑:
我刚刚意识到您添加了信号/槽标签。如果您碰巧使用 Qt,您可能需要 QSharedPointer (或类似的) 而不是 boost 指针实现。
The best option is to use a smart pointer implementation such as Boost's shared_ptr.
This allows you to pass around the pointers as needed, without worrying about the deletion.
Edit:
I just realized you had the signal/slot tag added. If by chance you're using Qt, you probably want QSharedPointer (or similar) instead of a boost pointer implementation.