Finally, I won't delete those last two news (for Info and testCase), but I don't care since it is just in last iteration and now program works fine. |
Consider not to create them with new at all. There's no obvious reason in your code to create them on the heap, so just write
TestCase testCase;
and use it with
testCase.SetInfo...
. Then you don't need any delete and no memory leaks out.
Imi: I have a question about the treatment of vectors about pointers:
If I make a new of a struct (like mine) and I put it inside a vector (considering that I did news for the pointers of my struct), should I make delete in any moment? |
if you put any pointers that have been created with new into vectors, then you have to delete them.
But you don't have to delete the vector itself (except you created the vector itself with new, but why would you do this?)
Maybe it becomes clear if you think of a std::vector<double> as a 1:1 replacement of a "new double[]" (it's not a 1:1, but roughly.. ;)
1 2 3 4 5 6 7 8 9 10 11
|
// creating
double* c_style = new double[n];
std::vector<double> cpp_style(n);
// assigning values
for (int i = 0; i < n; ++i) c_style[i] = 23.42;
for (int i = 0; i < n; ++i) cpp_style[i] = 23.42;
// deletion
delete [] c_style;
// nothing to do for cpp_style... use "cpp_style.clear()" to explicitly free the values.
|
After you mastered this way of using std::vector, look into the more advanced stuff you can do with vector's and how they are usually used in C++ programs (iterators, for_each etc).
The same way as you instinctively won't write
double** a[100]
(which creates an array of 100 different pointers to double), you shouldn't write
std::vector<double*>
(except, of course, you really want an array of 100 pointers instead of 100 double values).
Now if you thought this through for double, it isn't any different with structs. If you would write
MyStruct* p = new MyStruct[100];
write instead:
std::vector<MyStruct> v(100);
. If you don't do any "new" for the structs in the first case (only new[] for the whole array), so you don't need any new in the second case.
Some different world will emerge when you start using inheritance and subclasses and
have to store pointers created with new in arrays. Then it will get a bit hairy. But that's another story.
Ciao, Imi.