Explicit Destructor Invocation in C
In C , explicit destructor invocation is generally discouraged. However, there are specific instances where it is permitted.
Explicit Destructor Invocation and Class Template Specializations
As outlined in C 11 Standard Section 13.4.5, explicit destructor calls for objects of class template specializations allow for the explicit specification of template arguments. This is demonstrated in the example provided:
<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 instance, each explicit destructor call targets a specific class template specialization and executes the corresponding destructor. This is permissible because the destructor is part of the class template interface.
Other Cases of Explicit Destructor Invocation
Beyond the context of placement delete, there are limited use cases for explicit destructor invocation. One notable situation is the destruction of a trivial destructor object (an object whose destructor does not perform any actions). However, there is generally no practical purpose in performing this.
Reasons for Explicit Destructor Calls
In the case of placement new, explicit destructor calls are necessary to correctly destroy an object created in this manner.
When Not to Explicitly Invoke Destructors
Explicit destructor invocation should be avoided for local variables. As explained in the C FAQ, explicitly calling the destructor on a local variable may result in undefined behavior.
Conclusion
While explicit destructor invocation is generally not recommended, it is permitted in certain contexts, such as class template specializations and the destruction of placement-new objects. However, explicit destructor calls should be used cautiously and are primarily relevant for advanced C programming scenarios.
The above is the detailed content of When Is Explicit Destructor Invocation Permitted in C ?. For more information, please follow other related articles on the PHP Chinese website!