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:
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!