J
J
Julia2016-11-02 15:25:29
C++ / C#
Julia, 2016-11-02 15:25:29

What objects to delete in the destructor?

Hi all.
I wondered what objects should be removed.
For example, I remove widgets and fields.
And whether it is necessary to delete int or double. And why ?
I would like to read on this topic, maybe someone = what will advise
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-11-02
@Julila

After the body of the destructor has completed, destructors are automatically called for all fields of the object, in reverse order.
Int and double have zero destructors - but others are not needed.
In what cases it is necessary to write the destructor ourselves...
1. We own some resource, but the regular destructor does not destroy it.
• Simple (non-smart) pointer and allocated memory - this is well described by sitev_ru .
• An object-blocker, for example, a mutex (a mutex is an inter-thread synchronization primitive that prevents two threads from entering certain sections of the code at the same time).

class Mutex {
public:
  void enter();
  void leave();
}

class Lock {
public:
  Lock(Mutex& aMutex) : mutex(aMutex) { mutex.enter(); }
  ~Lock() { mutex.leave(); }
private:
  Mutex& mutex;
}

…
Mutex mutex;
{ Lock lock(mutex);
  // всё, что здесь, выполняется внутри мьютекса.
  // Даже если выпадет авария, из мьютекса корректно выйдем.
}

2. Complicated order of destruction. A singly linked list from std::unique_ptr will work with a standard destructor, but this is fraught with a stack overflow.
3. A complex ownership structure, and when destroyed, the object must be automatically taken away from the owners. In black is used in window frameworks in the manner of VCL and Qt. We delete the component - it is automatically taken from the owner.
From experience: if data structures are taken out into a separate object (well, use STL where possible), 80% of C ++ objects will have an automatic destructor.
PS. According to the results of estimates in a live project, ≈150 files (actually 219 files, but not all of our own; library destructors were not taken into account).
• Classes with a real destructor - about 30. Mostly system (W32Cs - fast Win32 mutex) or memory structures (Array1d, for example). There are three of them in the project itself (not in the programmer's personal library) (!): one is related to auto-ownership of someone else's XLSX library, two are related to background threads.
• Interfaces with an empty virtual destructor - about 40.
• And more destructors automatically added by Qt - by the number of forms, exactly 20.
• And a few empty destructors added at the request of the left heel of the linker.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question