Ok, so I want to write an accurate mark and sweep garbage collector in C ++. I hope that some solutions that can help me, as in all my pointers, will be wrapped in "RelocObject", and I will have one block of memory for the heap. It looks something like this:
class MemBlock
{
public:
void* Get( void ) { return m_ptr; }
private:
MemBlock( void ) : m_ptr( NULL ){}
void* m_ptr;
};
template<typename _Type_>
class TypedBlock
{
public:
_Type_* Get( void ) { return m_pObject; }
private:
TypedBlock( void ) : m_pObject( NULL ){}
_Type_* m_pObject;
};
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();
}
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(); }
TypedBlock<_Type_>* m_pRef;
};
typedef RelocObject<Impl::Foo> Foo;
void main( void )
{
Foo foo = Foo::New();
}
So, to find the “root” RelocObjects, when I select “RelocObject :: New”, I pass the pointer 'this' RelocObject to the allocator (garbage collector). The allocator then checks to see if the 'this' pointer is in the range of the memory block for the heap, and if so then I can assume that it is not the root.
, , , RelocObjects, .
RelocObjects (.. ) "" . , , RelocObjects. , .
Clang RelocObjects , .
, ? , . , Clang, .. - ?
, : Clang 'Foo' ( typedef RelocObject) FooB , - "", :
class FooB
{
public:
int m_a;
Foo m_ptr;
};
.