Game Programming Gems4 1.7 代碼錯誤

來源:互聯網
上載者:User

對象生存周期管理是C++工程最重要一個環節。關於此類問題《遊戲編程精粹》(GPG)系列一直有文章在提。比如第三冊 1.5 《基於控制代碼的智能指標》,第四冊1.7的《弱引用和Null 物件》。在GPG4 1.7給出的代碼中發現了一些問題。原始代碼如果放入實際工程結果會很不美妙。這裡提一下

原文對指標的封裝做如下處理:

template <class ResourceType> class ResPtr
{

public:

     //一些建構函式

    ResPtr(const ResPtr<ResourceType> & resPtr);
    explicit ResPtr(ResourceType * pRes);
    ResPtr(ResourcePtrHolder * pHolder = NULL);

public:

   //析構
    ~ResPtr();

private:

//用這個中介層封裝指標
    ResourcePtrHolder * m_pResHolder;
}

class ResourcePtrHolder
{
public:
    ResourcePtrHolder (IResource * p) : pRes(p) {}
    ~ResourcePtrHolder();

//使用者物件指標放這裡
    IResource * pRes;
};

 

template <class ResourceType> ResPtr<ResourceType>::ResPtr(ResourceType * pRes)
{
    m_pResHolder = new ResourcePtrHolder(pRes); //封裝原生指標時,在heap產生一個新ResourcePtrHolder對象
}

template <class ResourceType> ResPtr<ResourceType>::~ResPtr()
{//空析構
}

其他ResPtr代碼略,但值得一提的是沒有 delete   m_pResHolder  字樣...

也就是說假如直接使用ResPtr ,用一次就有一個  ResourcePtrHolder 對象泄露

 

代碼提供了另外一套引用計數的指標封裝版本,ResourcePtrHolder內使用了delete this 銷毀記憶體。但依然有個問題:

 

ResourcePtrHolder::~ResourcePtrHolder()
{
    delete pRes;
}

首先IResource 對外部要管理的指標類型做出了強制性的規定。必須是從IResource派生的類。其次是在holder析構時,不由分說把一個外部傳入要管理的對象指標的內容刪除。這樣強硬的策略我想無論放到哪裡都會導致異常巨大的問題。即便是採用引用計數版本,在holder計數到0再刪除自己,順帶刪除管理的對象,對於外部來講也是個黑洞。

 

1.7代碼的品質讓人驚詫,還不知道整本書有多少類似的

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.