三级运算在计算机,09年计算机三级辅导:MethodTable内存空间分配中加法运算算法...

09年计算机三级辅导:MethodTable内存空间分配中加法运算算法

分类:计算机等级|

更新时间:2008-12-13|

来源:教育联展网

在分析MethodTable具体分配内存实现的时候,看到了计算MethodTable的大小,然后分配空间的算法。其中有个加法运算实现的非常赞,特地截取出来。

所有的MethodTable的分配,都是通过methodtable中的一个static方法AllocagteNewMT来实现的,该方法定义如下:

MethodTable * MethodTable::AllocagteNewMT(EEClass *pClass,

DWORD dwVtableSlots,

DWORD dwGCSize,

DWORD dwNumInterfaces,

DWORD numGenericArgs,

DWORD dwNumDicts,

DWORD cbDict,

ClassLoader *pClassLoader,

BaseDomain *pDomain,

BOOL isInterface,

BOOL fHasGenericsStaticsInfo,

BOOL fNeedsRemotableMethodInfo,

BOOL fNeedsRemotingVtsInfo,

BOOL fHasThreadOrContextStatics

, AllocMemTracker *pamTracker

)

下面是该方法中计算大小的一段,采用模板来忽略类型带来的影响:

DWORD cbTotalSize = 0;

DWORD cbDicts = 0;

if (!ClrSafeInt::multiply(dwNumDicts, sizeof(TypeHandle*), cbDicts) ||

!ClrSafeInt::addition((DWORD)size, cbDicts, cbTotalSize) ||

!ClrSafeInt::addition(cbTotalSize, dwGCSize, cbTotalSize))

ThrowHR(COR_E_OVERFLOW);

然后转到addition((DWORD)size, cbDicts, cbTotalSize)的实现,加法的实现如下,加入了对各种情况的严格考虑:

// Returns true if safe, false on overflow

static inline bool addition(T lhs, T rhs, T &result)

{

//check for T first.

if(IsSigned())

{

//test for +/- combo

if(!IsMixedSign(lhs, rhs))

{

//either two negatives, or 2 positives, not mixed symbols

if(rhs < 0)

{

//two negatives

if(lhs < (T)(MinInt() - rhs)) //remember rhs < 0

{

return false;

}

//ok

}

else

{

//two positives

if((T)(MaxInt() - lhs) < rhs)

{

return false;

}

//OK

}

}

//else overflow not possible

result = lhs + rhs;

return true;

}

else //unsigned, and two symbols is mixed

{

if((T)(MaxInt() - lhs) < rhs)

{

return false;

}

result = lhs + rhs;

return true;

}

}

其中,涉及到中间调用的几个方法如下:

static bool IsSigned()

{

return( (T)-1 < 0 );

}

//Check if lhs and rhs is mixed Sign symbols

static bool IsMixedSign(T lhs, T rhs)

{

return ((lhs ^ rhs) < 0);

}

//both of the following should optimize away

static T MinInt()

{

if(IsSigned())

{

return (T)((T)1 << (BitCount()-1));

}

else

{

return ((T)0);

}

}

static T MaxInt()

{

if(IsSigned())

{

return (T)~((T)1 << (BitCount()-1));

}

//else

return (T)(~(T)0);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值