Click here to Skip to main content
15,860,844 members
Please Sign up or sign in to vote.
4.00/5 (1 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:

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


Can anybody explain, please?

Regards


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
Updated 11-Apr-12 9:59am
v2

1 solution

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
C++
else if (((_SIZT)(-1) / _Count) < sizeof (_Ty))


Throw bad allocation exception if the needed space exceeds the maximum space, by
C++
_THROW_NCEE(std::bad_alloc, NULL);


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.
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900