Home > Backend Development > C++ > body text

Why Can We Delete a Pointer to Const in C ?

Patricia Arquette
Release: 2024-11-03 09:29:03
Original
883 people have browsed it

Why Can We Delete a Pointer to Const in C  ?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template