code succinctness and aesthetics |
- Restricting variables to as tight a scope as possible is not about aesthetics. It's about cutting down the chance of something untoward happening to them. It also allows the compiler to optimize better in some cases, as it's easier to spot when you're done with a variable. Not a big deal on the small scale, I guess.
- Favouring ++i over i++ is not about aesthetics (at least to me). In some circumstances there can be performance implications for post-increment; by consistently using pre-increment you won't inadvertently use post increment in the wrong place.
Before I wrote my last post I downloaded your code and give it a go, as I could see any reason why it would work for ints but not doubles (strings are a different matter; your test case runs fine for me.
But I had adjusted your operator= to this...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
template<class dataType>
const myArray<dataType>& myArray<dataType>::operator=(const myArray<dataType>& rightArray)
{
if(this != &rightArray)
{
delete [] arrayPtr;
arrayLowerBound = rightArray.arrayLowerBound;
arrayUpperBound = rightArray.arrayUpperBound;
arraySize count = arrayUpperBound - arrayLowerBound;
arrayPtr = new dataType[arraySize];
for (int i = 0; i < arraySize; i++)
arrayPtr[i] = rightArray.arrayPtr[i];
}
return *this;
}
|
So I inadvertently fixed the problem which ne555 just pointed out: that the array size was being calculated on the wrong (old) bounds.
When I reinstate your version of operator=, the test case crashes (I tweaked your test code to add values automatically rather than manually, see below).
Andy
PS Modified setArrayData()
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
template<class dataType>
void myArray<dataType>::setArrayData()
{
if(arrayPtr != NULL)
{
int count = arrayUpperBound - arrayLowerBound;
for (int i = 0; i < count; i++)
{
dataType value = dataType();
genRandVal(value);
arrayPtr[i] = value;
}
}
}
|
which uses (non-template function)
1 2 3 4
|
void genRandVal(double& value)
{
value = (rand() % 100) / 3.0;
}
|
Plus added
srand(time(0));
to start of program, as per usual.