STL分配器问题 [英] STL allocator question

查看:128
本文介绍了STL分配器问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我刚刚在STL实现源中看到了这一点:

Hello everyone,

I just saw this in the STL implementation source:

template<class _Ty> inline
	_Ty _FARQ *_Allocate(_SIZT _Count, _Ty _FARQ *)
	{	// check for integer overflow
	if (_Count <= 0)
		_Count = 0;
	else if (((_SIZT)(-1) / _Count) < sizeof (_Ty))
		_THROW_NCEE(std::bad_alloc, NULL);

		// allocate storage for _Count elements of type _Ty
	return ((_Ty _FARQ *)::operator new(_Count * sizeof (_Ty)));
	}



我不明白的是:



What I don''t understand is this:

else if (((_SIZT)(-1) / _Count) < sizeof (_Ty))
    _THROW_NCEE(std::bad_alloc, NULL);



有人可以解释吗?

问候


而当我们这样做时,这又如何呢?



Can anybody explain, please?

Regards


And while we''r at it, what about this?

template<class _T1,
	class _T2> inline
	void _Construct(_T1 _FARQ *_Ptr, const _T2& _Val)
	{	// construct object at _Ptr with value _Val
	void _FARQ *_Vptr = _Ptr;
	::new (_Vptr) _T1(_Val);
	}



为什么将指针转换为void *?



Why cast the pointer to void* ?

推荐答案

1.
它将检查是否有足够的空间容纳新对象.最大空间将等于unsigned int的最大值,该最大值由(_SIZT)-1确定.然后,所需空间由sizeof(_Ty)* _Count确定.它应该写为
1.
It will check if there is enough space to hold new objects. The max space would be equal to max value of unsigned int, which is determined by (_SIZT)-1. The space needed is then determined by sizeof(_Ty) * _Count. It should be written as
else if (((_SIZT)(-1) / _Count) < sizeof (_Ty))



如果所需空间超过最大空间,则抛出错误的分配异常,方法是



Throw bad allocation exception if the needed space exceeds the maximum space, by

_THROW_NCEE(std::bad_alloc, NULL);



否则,请调用new运算符以分配原始内存空间.

2.

从我的角度来看,如果没有人超载新的放置位置,则可以使用非空指针来放置新的放置位置.

强制转换可确保调用placement new(或标准placement new)的void指针版本.

您也可以在Google上搜索运算符新",新表达式",放置新"和分配器类",以更好地理解.



Otherwise, call operator new to allocate raw memory space.

2.

From my point of view, it''s ok for placement new to use non-void pointer, if nobody overloads placement new.

The cast ensures that the void pointer version of placement new (or the standard placement new) is called.

You could also google "operator new", "new expression", "placement new", and "allocator class" for better understanding.


这篇关于STL分配器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆