好的,所以我想用 C++ 编写一个精确的“标记和清除”垃圾收集器。我希望做出一些可以帮助我的决定,因为我的所有指针都将包装在一个“RelocObject”中,并且我将为堆提供一个内存块。这看起来像这样:
// This class acts as an indirection to the actual object in memory so that it can be
// relocated in the sweep phase of garbage collector
class MemBlock
{
public:
void* Get( void ) { return m_ptr; }
private:
MemBlock( void ) : m_ptr( NULL ){}
void* m_ptr;
};
// This is of the same size as the above class and is directly cast to it, but is
// typed so that we can easily debug the underlying object
template<typename _Type_>
class TypedBlock
{
public:
_Type_* Get( void ) { return m_pObject; }
private:
TypedBlock( void ) : m_pObject( NULL ){}
// Pointer to actual object in memory
_Type_* m_pObject;
};
// This is our wrapper class that every pointer is wrapped in
template< typename _Type_ >
class RelocObject
{
public:
RelocObject( void ) : m_pRef( NULL ) {}
static RelocObject New( void )
{
RelocObject ref( (TypedBlock<_Type_>*)Allocator()->Alloc( this, sizeof(_Type_), __alignof(_Type_) ) );
new ( ref.m_pRef->Get() ) _Type_();
return ref;
}
~RelocObject(){}
_Type_* operator-> ( void ) const
{
assert( m_pRef && "ERROR! Object is null\n" );
return (_Type_*)m_pRef->Get();
}
// Equality
bool operator ==(const RelocObject& rhs) const { return m_pRef->Get() == rhs.m_pRef->Get(); }
bool operator !=(const RelocObject& rhs) const { return m_pRef->Get() != rhs.m_pRef->Get(); }
RelocObject& operator= ( const RelocObject& rhs )
{
if(this == &rhs) return *this;
m_pRef = rhs.m_pRef;
return *this;
}
private:
RelocObject( TypedBlock<_Type_>* pRef ) : m_pRef( pRef )
{
assert( m_pRef && "ERROR! Can't construct a null object\n");
}
RelocObject* operator& ( void ) { return this; }
_Type_& operator* ( void ) const { return *(_Type_*)m_pRef->Get(); }
// SS:
TypedBlock<_Type_>* m_pRef;
};
// We would use it like so...
typedef RelocObject<Impl::Foo> Foo;
void main( void )
{
Foo foo = Foo::New();
}
因此,为了在“RelocObject::New”中分配时找到“根”RelocObjects,我将 RelocObject 的“this”指针传递给分配器(垃圾收集器)。然后分配器检查'this'指针是否在堆的内存块范围内,如果是,那么我可以假设它不是根。
因此,当我想使用位于每个子对象内的零个或多个 RelocObjects 从根跟踪子对象时,问题就来了。
我想使用“精确”方法在类(即子对象)中找到 RelocObjects。我可以使用反射方法并让用户注册他或她的 RelocObjects 在每个类中的位置。但是,这很容易出错,所以我想自动执行此操作。
因此,我希望在编译时使用 Clang 在类中查找 RelocObjects 的偏移量,然后在程序启动时加载此信息,并在垃圾收集器的标记阶段使用它来跟踪和标记子对象。
所以我的问题是 Clang 可以帮忙吗?我听说您可以在编译期间使用其编译时挂钩收集各种类型信息。如果是这样,我应该在 Clang 中寻找什么,即有没有做这种事情的例子?
明确一点:我想使用 Clang 在 FooB 中自动查找“Foo”(这是 RelocObject 的 typedef)的偏移量,而无需用户提供任何“提示”,即他们只写:
class FooB
{
public:
int m_a;
Foo m_ptr;
};
提前感谢您的帮助。