Removing a vector of pointers passed to a class
I have an abstract class module
from which certain modules derive. At runtime, I parse the config file and define the specific module type of each module in the config file:
std::vector<module*> modules;
module *temp;
//Let nm be the result of parsing as a std::string
if(nm == "type1")
{
temp = new module_1(...);
}
else if(nm == "type2")
{
temp = new module_2(...);
}
else if(nm == "type3")
{
temp = new module_3(...);
}
else
{
//Syntax error
return -1;
}
modules.push_back(temp);
partition p;
p.modules = modules;
passing the vector to the modules
class partition
:
class partition
{
public:
//Member functions
private:
//...Other variables
std::vector<module*> modules;
};
What's the correct way to free memory for these module pointers once I'm done with them? I tried to remove them in the destructor for the class partition
as follows, but ended up with a segmentation error:
partition::~partition()
{
for(unsigned i=0; i<modules.size(); i++)
{
delete modules[i];
}
}
source to share
It depends on how you want to deal with ownership and if the section will have value semantics. Consider what happens if you copy a section:
Whether the copy of the section will separate modules from the original. Are the changes in the module changed between sections?
If yes, you should use std::shared_ptr
for your sections. All the pain is gone.
If not, run a copier statement and an assignment statement for your section, which makes a deep copy of the list of modules. Implement a destructor that removes every module in the list. This is safe since each section has its own module objects.
Overall, I prefer the second approach. If you don't want to embed a deep copy, just do partition
noncopyable or move-only and use std::unique_ptr
to handle the delete.
source to share