And... isn't the same with new/delete? How can new/delete prove better that the memory is freed when it should be?
|
No. Look at my second example, and tell me where I used new or delete. You are right that new and delete do not prove anything better than malloc and free. My point with the STL container is that you can avoid the new/delete in the first place. Yes,
internally vector is dynamically allocating and freeing memory, but to helios' point, the vector destructor ensures that memory used by the vector is freed.
You are trying to combine vectors with arrays and that makes things hard. You should rarely ever need to dynamically allocate vectors or any other STL container for that matter.
To use your original example:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
struct C {
int a, b;
};
struct B {
std::vector<C> cs;
// Don't need total_C; use cs.size() to determine number of elements
};
struct A {
std::vector<B> bs;
// Don't need total_B; use bs.size() to determine number of elements
};
|
Done. Memory will be allocated and freed correctly at the right times already, without you having to write a single line of executable code.
Your last example above is wrong because you are confusing vectors and arrays.
declares the variable "a" to be a pointer to an A. Thanks to C, "a" can also be thought of as an array of A's.
has type vector<A>*, not A*. Consequently, you would need to declare "a" as
|
vector<A>* a = new vector<A>();
|
Here is the correct way:
1 2 3
|
A a;
a.bs.push_back( B() );
a.bs.back().push_back( C() );
|
The first line of code declares a variable of type A.
The second line adds a new B to the end of A's "array".
The third line accesses the last element of A's "array" and adds a new C to it.