Home > Backend Development > C++ > body text

Why Doesn't `delete` Automatically Set Pointers to NULL in C ?

Linda Hamilton
Release: 2024-11-24 22:00:18
Original
456 people have browsed it

Why Doesn't `delete` Automatically Set Pointers to NULL in C  ?

Why Doesn't Delete Automatically Assign NULL to Pointers?

The C language standard does not mandate the automatic setting of pointer values to NULL after invoking the delete operator. While this may seem counterintuitive, there are several reasons for this decision.

Performance

As mentioned in the question, an additional instruction to set the pointer to NULL could potentially impact the performance of delete operations, especially in performance-critical code.

Const Pointers

Another potential issue is that some pointers may be declared as const. For these pointers, attempting to change their value after a delete operation is not possible. While it could be argued that a special case could be made for such pointers, the standard opted to maintain consistency by not modifying the pointer value in all cases.

Non-Lvalue Arguments

The delete operator can accept non-lvalue arguments, such as rvalue references. In these scenarios, it is not possible to modify the pointer's value. This poses a technical limitation for the standard to ensure consistency in behavior for all argument types.

Bjarne Stroustrup's Explanation

Bjarne Stroustrup, the creator of C , has addressed this issue:

  • He had expected implementations to include a feature that automatically zeros out lvalue operands after delete, but this practice has not gained widespread adoption.
  • However, he emphasizes that delete's argument may not always be an lvalue, which introduces technical difficulties for the standardization of this behavior.

Therefore, while deleting a pointer in C does not automatically set it to NULL, the standard has considered various factors such as performance, const pointers, non-lvalue arguments, and consistency to arrive at this decision.

The above is the detailed content of Why Doesn't `delete` Automatically Set Pointers to NULL 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