CheckReturn(檢查返回值)

Loki庫提供了一種方法,要求函數返回後,使用者必須對其進行檢查或則賦值。以必須判斷指針爲例進行說明。

自己寫的代碼簡化了很多

CheckReturn.h

#pragma once
#include <assert.h>

template<class T>
struct TriggerAssert
{
 static void run(const T&)
 {
  assert( 0 );
 }
};

// 檢查函數返回值是否被賦值了,如果沒有被賦值,則認爲是非法的。必須給返回值賦值,即必須有所有權,不能出現中間變量
template<typename T, template<typename T> class TAssert = TriggerAssert>
class CCheckReturn
{
public:
 /// Conversion constructor changes Value type to CheckReturn type.
 inline CCheckReturn( const T* value )
  : m_value( value ), m_checked( false )
 {

 }

 /// 轉移所有權
 inline CCheckReturn( const CCheckReturn & that ) :
 m_value( that.m_value ), m_checked( false )
 { that.m_checked = true; }

 /// 必須轉換成bool檢查
 // 此處也可以將bool替換成T表示必須賦值
 inline operator bool ( void )
 {
  m_checked = true; // 被轉換過了
  return NULL != m_value;
 }
 
 inline ~CCheckReturn( void )
 {
  // asset或則其它方式也可以
  if (!m_checked)
   TriggerAssert<const T*>::run(m_value);
 }
private:
 const T* m_value;
 mutable bool m_checked; //是否被check過了。如果調用過operator則會賦值爲true
};


測試使用。

#include "StdAfx.h"
#include "TestCheckReturn.h"
#include "CheckReturn.h"

class CTestPtr
{

};

CCheckReturn<CTestPtr> GetPtr()
{
 return CCheckReturn<CTestPtr>(new CTestPtr);
}
 
void CTestCheckReturn::Test()
{
 CCheckReturn<CTestPtr> aa = GetPtr();

 //if (aa) // 如果沒有這句話,退出時就會進入我們的斷言了
 {

 }
 int ii = 10;
}


我們可以根據這個思想實現我們想要的其它檢查


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章