Skip to main content
GameDev.net gamedev.net
🔒 Locked

Array Class Deletion before Creation

Started by Webbster Feb 12, 2005 at 8:19 AM 4 replies 1.7k views
Original Post
Webbster
Webbster
In my array class ( a generic type using templates btw ) I specify a constructor that takes a 32-bit integer variable to be the number of cells in the array. However in my constructor I want to determine whether or not the requested cell value exceeds 65,535 if it does, dont create the array. Heres the constructor

// Constructor
CArray( int iSize )
{
	// Check for valid size limit
	if( iSize > 65535 )
	{
		// Write Error Message, eventually
		return;
	}
	else
	{
		m_pArray = new DType[ iSize ];	// Create the Array
		m_iSize = iSize;		// Set Array Size
	}

	return;
}

Obviously by stating return in the constructor I'm not achieving anything (dont really know if I should actually do that either but, meh!). At first I thought saying delete this; would be the answer but no, it doesn't work. How can I avoid my array class creating the array if the number of cells is greater than I ever want it to be? - Adam
ToohrVyk
ToohrVyk
I'm not sure an exception in a constructor is the best thing to do. Before the body of the constructor is even reached, memory is allocated and members are initialized.

If a constructor is called, the object WILL be instantiated and will have to be destroyed afterwards. Therefore, your best bet would be to prevent calling the constructor by making it private and implementing a static function that throws an exception on bad input, and calls the constructor on correct input.

But in a case like yours, I take it the constructor should never be called with an incorrect argument, so you might as well use assert( ) to check if the size is acceptable, in order to catch bugs if you ever pass an incorrect value.
snk_kid
snk_kid
#include <cstddef>template < typename Tp >struct CArray {  typdef size_t size_type;  const size_type max_size = 65535;  //.....  CArray(size_type  n): m_iSize(n), m_pArray((n <= max_size) ? new Tp[n] : 0) {}  //...};


Is there reason not to use the standard library dynamic array std::vector? because its not very efficent way to implement it and not very exception safe either.
Webbster
Webbster
P.S. I love how you threw in "( a generic type using templates btw )". Congratulations. Would you like a cookie?

--------------------------------

Is that supposed to be sarcasm? I really can't tell when your saying it on a message board.

Anyway, the reason I wish to impose this limit is for the sake of file sizes in my project. The program using this class will be writing arrays to file and I wish to be able to hold a file size limit, so this is obviously one way of doing it.

Further help on how I can achieve this limit would be helpfull as the AP obviously wasn't.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.