围绕shared_ptr构建对象系统
我正在使用 shared_ptr
作为我正在开发的玩具语言的垃圾收集,该语言可编译为 C++。我的对象派生自上面的公共基类,其中有字符串和数字,然后有向量和地图。 C++ 端的所有内容都包装在 shared_ptr
中传递,因此我的容器实际上保存 shared_ptr
,这样当它们被销毁时,它们的内容也会被销毁。这个方案是有效的,但感觉有点奇怪,因为作为基础对象的容器持有 shared_ptr
。我的设计有缺陷吗?如果是的话,围绕这种方法的替代层次结构是什么?
I am using shared_ptr
as my garbage collection for a toy language that I am working on which compiles to C++. My objects derive from a common base class above that there are strings and numbers then there are vectors and maps. Everything on the c++ side is passed wrapped in shared_ptr
s so my containers actually hold shared_ptr
so that when they get destroyed their content is destroyed too. This scheme works but it feels a bit weird in that containers that are base objects are holding shared_ptr
s. Is there a flaw with my design? If yes what would be an alternative hierarchy around this approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下是我的设置方法:
请注意,此方案中的 ToyLang 数组是指针向量,提供语言引用语义。事实上,这在动态语言中很常见:Lisp、Python 和其他语言都是这样工作的。只要您没有循环引用,
shared_ptr
的引用计数就会为您提供适当的垃圾回收。Here's how I'd set this up:
Note that ToyLang arrays in this scheme are vectors of pointers, giving the language reference semantics. This is in fact quite common in dynamic languages: Lisp, Python, and others work like that. As long as you don't have circular references,
shared_ptr
's reference counting will give you proper garbage collection.