This is an extension of this question . I have searched on the web but couldn't find a satisfactory answer.
I have a class A
which defines a vector that contains a number of instances of class Region
. The memory handling for these Region
instances need to be managed by Class A
My questions are:
1. In the following code snippet, do I need to explicitly delete these instances in the desctuctor of class A?
2. Should I create instances as new Region(i)
? Is it better over the first option (not using new
) Class A is quite a large object. How should I determine whether to use new or not?
3. If Answer to #2 is yes, how should I delete these instances in the destructor ? delete Region(i)
(in a for loop) or delete [] reg
?? I am guessing former way is the correct way, but want to confirm.
4. Other than "Region instances are not deleted" , do you see any obvious memory leak... especially in the construction of Region object in A
's constructor?
class Region{
public:
Region(int num);
int number;
std::vector <elemt*> elements;
int info;
}
class A{
public:
std::vector<Region> reg;
const int numOfRegions = 100;
}
A::A(){
int i;
for ( i=0; i<numOfRegions; i++){
reg.push_back(Region(i));
}
}
A::~A(){
// How should the elements within vector Region be deleted??
// Should I use "new" to allocate memory to instances of Region()
}
UPDATE: A BIG Thanks to all who answered!