Exception-throwing Functions

closed account (zb0S216C)
I'm in need of assistance. I have a function that allocates memory for the specified amount of elements, of the template type. However, I want the function to throw a bad_alloc exception if the allocation fails.

Here's my code so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template < typename __typename__ >
bool alloc( __typename__ *&block, const int len, const __typename__ &obj ) throw( std::bad_alloc )
{
    if( len <= 0 )
        return false;

    if( !block )
    {
	block = ( new( std::nothrow )__typename__[ len ] );

	if( !block )
	    return false;
	
	for( int loop( 0 ); loop < len; loop++ )
		block[ loop ] = obj;

	return true;
    }

    return false;
}


In the code above, I don't know if bad_alloc is thrown if the allocation of block fails. If bad_alloc isn't thrown automatically, how do I throw the exception? Do I need a try block?

Wazzak
If you want std::bad_alloc to be thrown, how come you're using the nothrow version of new[]?
It will return 0 on failure, the normal one throws a bad_alloc exception on failure.
closed account (zb0S216C)
OK, so if I remove std::nothrow, a bad_alloc exception is thrown if new fails? If that's the case, will the raised bad_alloc exception be thrown again by the function?

Wazzak
closed account (3hM2Nwbp)
The exception should propagate up until it's either handled or reaches the main method.

*You can test it for yourself by trying to allocate an insanely huge amount of memory.
Last edited on
Topic archived. No new replies allowed.