C++ classes destructors | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C++ classes destructors

"The destructor is called then the object is deleted." Can someone explain when is an objekt deleted? At the program execution? Does that mean that all destructors from all classes will calld at the end of a programm? Thank you in advance!

12th Aug 2020, 7:43 PM
Eert Aniemit
Eert Aniemit - avatar
3 Answers
+ 2
No, not all destructors will be called at the end of the program. Imagine just how much memory overhead you would have that way if all local variables, all copies that were made at some point, all allocations would persist until then. You would just bulk up unnecessary memory that is often no longer required. There are four ways an object can be deleted, most of which C++ takes care for automatically: 1. Only static (and global) variables remain from program start until program end, which is necessary for them. 2. Objects local to a thread will be deleted if the thread finishes running. 3. The most common way for objects to be deleted is to go out of scope, which means that the scope they belong to reaches it end. For example, objects created locally in a function will be destroyed once the function ends. 4. Objects you allocated dynamically will be destroyed when you deallocate them. This is the only thing you have to do yourself. More information: https://arne-mertz.de/2016/01/c-object-lifetimes/
12th Aug 2020, 8:30 PM
Shadow
Shadow - avatar
+ 3
@Shadow: Nice, and thanks for that link! There is one case where external level and static variables (1.) dont exist for the full duration: when loading in shared objects/dynamic link libraries at runtime (-ldl). And for (4.) std::unique_ptr and std::shared_ptr helps a lot
12th Aug 2020, 8:50 PM
Ockert van Schalkwyk
Ockert van Schalkwyk - avatar
+ 1
Ockert van Schalkwyk: Interesting, I didn't even think about such possibilities regarding the DLL's. Thanks for adding that!
13th Aug 2020, 12:41 AM
Shadow
Shadow - avatar