Deleting a Pointer to Const (T const*)
In C , it is a known fact that non-const member functions cannot be called using a const pointer. However, a common exception is encountered when deleting a pointer to const, even though it calls the class's destructor, which is not a const method. This apparent anomaly raises the question: why is this allowed?
The answer lies in supporting the necessary destruction of objects. When objects are created dynamically, it is essential to have a way to delete them, even if they are const. This is achieved by allowing the deletion of const pointers, despite the restriction on modifying const objects.
The following code demonstrates this behavior:
<code class="cpp">// dynamically create object that cannot be changed const Foo * f = new Foo; // use const member functions here // delete it delete f;</code>
Another example shows that this behavior is not limited to dynamically created objects:
<code class="cpp">{ const Foo f; // use it } // destructor called here</code>
If destructors could not be called on const objects, it would prohibit the use of const objects entirely. This allowance ensures the proper destruction of objects, regardless of their const status.
The above is the detailed content of Why Can We Delete a Pointer to Const in C ?. For more information, please follow other related articles on the PHP Chinese website!