开发者

C++ - is a pointer to a single value same as a size 1 dynamic array?

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开发者_如何学Python 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?


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


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;


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜