Reputation: 563
In reading up on smart pointers in C++, most of the information comes with a caveat :
"Be warned that a smart pointer destructor will (may) not be called in circumstances like an abnormal exit (by calling std::abort or std::exit()), or when an exception propagates out of a thread's primary function or when a method declared noexcept throws an exception".
My question is that in all these cases, the program terminates eventually in which case the memory the smart pointer was pointing to is claimed back by the OS when the page tables for the process are cleared (I know that the C++ standard doesnt discuss page tables and virtual memory but I am mentioning it here because this is the standard practice in majority of the OSes out there).
So why is this warning issued? What is the worst thing that can happen if the destructor is not called? Or is this a warning that I need to be aware of when I use a smart pointer to manage a resource other than memory? If yes, then what are such resources?
Upvotes: 5
Views: 495
Reputation: 16726
As I already said in my comments the situations that the standard is talking about are exceptional circumstances that should not happen. Chances are very high that if they happen your program will not function properly anymore. So it is terminated and the standard does not guarantee that all destructors are called properly.
The solution is to prevent the circumstances to happening.
abnormal exit (by calling std::abort or std::exit())
Don't call abort
or exit
. Let all called functions return and let main
do a return
.
or when an exception propagates out of a thread's primary function
Catch all exceptions in main
. Then return
. Or if there are no global objects you can also abort
.
or when a method declared noexcept throws an exception".
Don't throw in noexcept
functions.
The problems that can arise are not only memory related. A smart pointer that is deleting the pointer it holds triggers the destructor of the object that it points to. The object might hold external resources. These could be for example a file (or socket) that shall be flushed (writing out buffered I/O) before it is closed. It could also be something low level hardware related like a GPIO that for example turns a light on during an operation and turns it off in the destructor.
Upvotes: 2