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;
}
我们可以根据这个思想实现我们想要的其它检查