我想基于引用计数器为脚本引擎做某种垃圾收集:
class HeapValue
{
private:
size_t _refCount;
public:
HeapValue()
: _refCount( 0 )
{ }
virtual ~HeapValue() { }
inline void reference() throw()
{
++this->_refCount;
}
inline void unreference() throw()
{
if( 0 == --this->_refCount )
{
delete this;
}
}
};
但我的对象不仅是 HeapValues,它们也是 Scopes:
class Scope
{
protected:
std::map< std::string, Value > _vars;
public:
inline Value & getRef( const std::string & name ) throw()
{
return this->_vars[ name ];
}
inline Value getCpy( const std::string & name ) const
{
std::map< std::string, Value >::const_iterator itr = this->_vars.find( name );
if( this->_vars.end() != itr )
{
return itr->second;
}
else
{
throw std::exception( "Scope::getCpy() - Accessing undeclared indentifier in readonly mode." );
}
}
};
class Object : public Scope, public HeapValue
{
};
假设我创建了一个对象,当类 HeapValue 删除自身时究竟会发生什么?我假设它不会调用 Scope 析构函数,因为 Scope 不是 HeapValue 吗?
谢谢你:)
编辑:添加类对象定义
编辑:
我的值类是一个变体:
class Value
{
private:
union
{
int _i;
double _r;
std::string * _s; // Owned/copied
Object * _o; // Not owned/copied
}
_data;
// etc...
};
和:
class HeapValue
{
//...
inline void reference() throw()
{
++this->_refCount;
}
inline void unreference() throw()
{
--this->_refCount )
}
};
Value & Value::operator = ( const Value & val )
{
switch( this->_type )
{
// ...
case E_OBJECT :
switch( val._type )
{
// ...
case E_INTEGER :
this->_data._o->unreference();
if( this->_data._o->getRefCount() == 0 ) delete this->_data._o; // Deletion moved here, outside of HeapValue ?
this->_data._i = val._data.i;
this->_type = E_INTEGER;
break;
// ...
}
}
// ...
}
最佳答案
当unreference
调用delete this
时,它会调用虚方法(因为析构函数是虚的)。如果对象是 Object
类型,则虚拟调用将指向 Object
的析构函数,该析构函数将调用它的所有父级析构函数,包括 Scope
的。
只是不要通过 Scope
指针删除 Object
实例,也不要在堆栈上分配或复制 HeapValue
实例。
也就是说,我会使用 std::shared_ptr
进行引用计数。
关于C++/A 类 : public B, 公共(public) C/~C() 上的 B 发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25054218/