围绕shared_ptr构建对象系统

Building an Object System Around shared_ptr

本文关键字:对象 系统 构建 ptr shared 围绕      更新时间:2023-10-16

我正在使用shared_ptr作为我的垃圾收集器,用于我正在开发的一种编译为c++的玩具语言。我的对象派生自上面的一个公共基类,有字符串和数字,然后有向量和映射。c++方面的所有内容都被包裹在shared_ptr s中,所以我的容器实际上持有shared_ptr,这样当它们被破坏时,它们的内容也被破坏了。这个方案工作,但感觉有点奇怪的是,容器是基本对象持有shared_ptr s。我的设计有缺陷吗?如果是,围绕这种方法的另一种层次结构是什么?

我是这样设置的:

namespace toylang {
class Object;
// main handle type; use this for all object references
// replace with boost::intrusive_ptr or similar if too inefficient
typedef std::shared_ptr<Object> obj;
class Object
{
    // whatever
};
class Number : public Object
{
    int x;
    // etc
};
class Array : public Object
{
    std::vector<obj> a;
    // etc
}

请注意,该方案中的ToyLang数组是指针的向量,从而提供了语言的引用语义。事实上,这在动态语言中非常常见:Lisp、Python和其他语言都是这样工作的。只要您没有循环引用,shared_ptr的引用计数将为您提供适当的垃圾收集。