Reputation: 883
I have an abstract module
class that specific modules derive from. At runtime, I parse a config file and determine the specific module type of each module within 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;
handing off the vector modules
to a partition
class:
class partition
{
public:
//Member functions
private:
//...Other variables
std::vector<module*> modules;
};
What's the proper way to deallocate the memory for these module pointers once I'm done with them? I tried to delete them in the destructor for the partition
class as follows, but wound up with a segmentation fault:
partition::~partition()
{
for(unsigned i=0; i<modules.size(); i++)
{
delete modules[i];
}
}
Upvotes: 3
Views: 131
Reputation: 59811
That depends on how you want to handle ownership and if a partition is going to have value semantics. Think about what should happen if you copy a partition:
Is the copy of the partition going to share the modules with the original. Are changes in a module to be shared between the partitions?
If yes, you should use a std::shared_ptr
for your partitions. All pain is gone.
If not, implement a copy-constructor and assignment operator for your partition that performs a deep-copy of the modules list. Implement a destructor that deletes each module in the list. This is safe, because each partition has its own module objects.
In general, I favor the second approach. If you don't want to implement the deep-copy, just make partition
noncopyable or move-only and use std::unique_ptr
to handle the deletion.
Upvotes: 2