Home > Article > Backend Development > When is it Okay to Explicitly Call a Destructor in C ?
Explicit Destructor Calls: When and Why
In general, explicit destructor calls are not recommended in C . However, exceptions exist, as exemplified in Section 13.4.5 of the C 11 Standard:
<code class="cpp">template<class T> struct A { ~A(); }; void f(A<int>* p, A<int>* q) { p->A<int>::~A(); // OK: destructor call q->A<int>::~A<int>(); // OK: destructor call }</code>
In this example, the explicit destructor calls are permissible because the objects in question were created using placement new. To destroy such objects, you must explicitly invoke their destructors.
Beyond placement delete, there are few legitimate reasons to call a destructor explicitly. One possibility is to manually destroy a trivially destructible object, though this is not particularly useful.
Additional Note
A commonly cited exception to the rule of avoiding explicit destructor calls pertains to local variables. However, this is not accurate; you should not explicitly call destructors on local variables.
The above is the detailed content of When is it Okay to Explicitly Call a Destructor in C ?. For more information, please follow other related articles on the PHP Chinese website!