tags:

views:

157

answers:

7

If I have:

std::size_t bagCapacity_ = 10;
std::size_t bagSize = 0;
A** bag = new A*[bagCapacity_];

while (capacity--)
{
  bag[capacity] = new A(bagSize++); //**here I'm loading this array from the end is it ok?**
}

And also can I delete those object from starting at the end of the array?

while (capacity--)
{
  delete bag[capacity];
}

Question in a code.

+1  A: 

There's no forced order to access an array, so your code is fine.

KennyTM
+1  A: 

Yes, once you've allocated the bag array, you can iterate over it however you want. The point of arrays is to be randomly accessible in constant time. What you're doing is fine.

Chris Schmich
+8  A: 
here I'm loading this array from the end is it ok?

Yes, that is fine. You can fill the elements anyway you like.

delete[] bag[capacity];

This code is wrong. bag[capacity] is of type A* which is allocated using new and not new[] hence you should not do delete[] you should do only delete bag[capacity]; to delete individual A objects. At the end you should be delete[] bag to delete the memory allocated for the bag.

Naveen
+1  A: 

I'm not entirely sure whether you want an array of arrays of A or an array of A pointers. If you want an array of arrays, then you should be doing

bag[capacity] = new A[bagSize++];

(note the square brackets) but otherwise the code looks good. However, if it's the second case (array of A pointers), then you should only do

delete[] bag;

(i.e. no delete[] in a loop).

Alex - Aotea Studios
+1  A: 

The code is fine except for the delete part. It should be delete bag[capacity]; since you are not deleting the array but an instance of A that is a member of the array. After that, you should also perform delete[] bag to delete the allocated array for bag.

I'm wondering why you put bagCapacity_ in std namespace? Perhaps you want it in your own namespace?

Chris Henry
A: 

There is one part of your code that's particularly disturbing:

std::bagCapacity_ = 10;

This seems to indicate that you're creating a variable named bagCapacity in the std namespace. Unless I'm misunderstanding what's going on here, this is strictly verboten -- there are only a few things you're allowed to add to the std namespace (primarily specializations of templates that are already there).

I'm also left wondering what you're doing here. Using new[] is nearly always a mistake. What you're writing looks suspiciously like a mediocre imitation of a vector, so unless this is something on the order of a class assignment intended to teach some specific (rather poor) technique, you'd probably be better off asking about what you're actually trying to accomplish, and getting advice about a good way to do that instead.

Jerry Coffin
A: 

It's quite OK to set array elements in any order. But you are missing delete[] operation!

Allopen