C++管理共享对象的句柄问题

发布于 2024-08-25 05:12:52 字数 455 浏览 5 评论 0原文

是否有管理由 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千と千尋 2024-09-01 05:12:52

最好的选择是使用智能指针实现,例如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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文