C ++ / A类:公共B,公共C / B在~C()上会发生什么?

时间:2014-07-31 08:30:44

标签: c++ inheritance polymorphism virtual destructor

我想基于引用计数器为脚本引擎进行某种垃圾收集:

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
{
};

假设我创建了一个Object,当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;
        // ...
        }
    }
    // ...
}

1 个答案:

答案 0 :(得分:1)

unreference调用delete this时,它会进行虚方法调用(因为析构函数是虚拟的)。如果对象的类型为Object,则虚拟调用将指向Object的析构函数,该析构函数将调用其所有父级的析构函数,包括Scope

不要通过Object指针删除Scope个实例,也不要在堆栈上分配HeapValue个实例或复制它们。

那就是说,我会使用std::shared_ptr进行引用计数。