views:

149

answers:

4

I have this snippet of code which I am considering to simplfy:

if (numberOfResults > 1)
{

    trackResult_ = new TrackResult[numberOfResults];
 for (int i=0; i < numberOfResults; i++)
  {
   // Make a deep copy
   TrackResult tempResult = result[i];
   TrackResult * clone  = new TrackResult(tempResult);
   trackResult_[i]  = *clone;
  }

 storeJointResults(trackResult_, numberOfResults);
}
else
{
 trackResult_ = new TrackResult(*result);
}

(I have 'no choice' but to use a simple dynamic array here. Vectors are deemed 'too complicated' at my workplace)

I am wondering if I can get away with

// even if we just have one result, we init an array size of one
trackResult_ = new TrackResult[numberOfResults];

However, I have in several points check for the number of results and act accordingly

if (numberOfResults_ == 1)
{
   velocity = trackResult_.velocity;
}

Would those code still work? If not, why?

+3  A: 

No, you need to ensure you match the correct scalar delete or array delete[] depending on whether you say new TrackResult[n]; or new TrackResult;.

Also, this leaks memory for each loop iteration:

 TrackResult tempResult = result[i];
 TrackResult * clone  = new TrackResult(tempResult);
 TrackResult_[i]  = *clone;
Evän Vrooksövich
That leaky "deep copy" should just be `trackResult_[i] = result[i];`. It would be even better to persuade the workplace that using standard containers, and replacing this whole mess with `trackResult_ = result;`, is not "too complicated".
Mike Seymour
+6  A: 

The array of size 1 does not need to be a special case.

When you allocate a dynamic array you are given a pointer to the first element. If the array is of size 1, this is pretty much indistinguishable from just having allocated a single instance of the object.

Your special case usage would work if you changed the . to an -> However I'd recommend not special-casing it and just use trackResult_[0].velocity

Alex Deem
Note that you must use delete[] not simply delete on dynamically allocated arrays (even if it is of size one)
Alex Deem
+1  A: 

I agree with Alex, using the . operator on a pointer is not my recommended style either, so those other points ought to be changed anyhow, and thus not discourage you from simplifying the piece of code you mention.

S.C. Madsen
+3  A: 

How are vectors too complicated? If anything, the simplify your code.

Fred
I have no idea. It's my supervisor who whack at me for using vectors. Making the problem worse is that his code does not use std containers. He was concerned about speed.
Extrakun