Click here to Skip to main content
13,402,312 members (47,617 online)
Rate this:
Please Sign up or sign in to vote.
See more:
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?


Edit: 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);

Why cast the pointer to void* ?
Posted 11-Apr-12 10:53am
Updated 11-Apr-12 10:59am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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);

Otherwise, call operator new to allocate raw memory space.


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.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.180218.2 | Last Updated 7 May 2012
Copyright © CodeProject, 1999-2018
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100