0

My question concerns whether I explicetely need to declare a destructor in my main class and in the QSharedData's inherited one, in order to prevent memory leaks. In this example I have an Employee class which handles its data through EmployeeData.

So do I need to declare

~EmployeeData(){}

and

~Employee()

to prevent memory leaks or it's handled by QSharedData itself that deallocates all its resources even without an explicit destructor, when Employee gets out of scope?

Here an example being implemented:

class EmployeeData : public QSharedData
{
public:
   EmployeeData() {}
  ~EmployeeData(){}
  // Some data here
   EmployeeInfo *info=nullptr;
};

Employee::Employee()
{
   data = new EmployeeData();
   data->info = new EmployeeInfo();
}

Employee::~Employee()
{
   if(data)
   {
     delete data->info;
   }
delete data;
}

Thanks in advance

Spatz
  • 21
  • 1
  • 7
  • Hold it by `std::unique_ptr`. That will give you a decent default adherence to the [rule of three, five or zero](http://en.cppreference.com/w/cpp/language/rule_of_three). The info pointee isn't handled by `QSharedData`. – StoryTeller - Unslander Monica Jan 15 '18 at 11:24
  • 1
    Also, what's the point of using `QSharedData` if you are calling `delete` yourself? – StoryTeller - Unslander Monica Jan 15 '18 at 11:27
  • Hi @StoryTeller, thanks for the answer. Of course I can use `unique_ptr` but my question concerns `QSharedData`. I'd like to know if a `QSharedData`'s derived class can rely on `QSharedData` for autonomously deleting its resources. – Spatz Jan 15 '18 at 11:46
  • 1
    I'd be really surprised if `QSharedData` auto-magically freed raw, randomly allocated pointers. – StoryTeller - Unslander Monica Jan 15 '18 at 11:47
  • Then I should only move `delete data->info` in `~EmployeeData(){}` and not worrying about `~Employee()` ' s implementation ? – Spatz Jan 15 '18 at 11:50
  • If `data` is a QSharedPtr or the like, then yes. The compiler generated `Employee` destructor will do the right thing. – StoryTeller - Unslander Monica Jan 15 '18 at 11:51
  • With the rule of 3/5 applied to `Employee`, then I need only `EmployeeData` ' s destructor being defined, in case it doesn't have an automatic ref counter to all its members. – Spatz Jan 15 '18 at 12:08

0 Answers0