Is the pointer guaranteed to preserve its value after `delete` in C++?(指针是否保证在 C++ 中的“删除之后保留其值?)
问题描述
灵感来自这个问题.
假设在 C++ 代码中我有一个有效的指针并正确地删除它.根据 C++ 标准,指针将变为无效(3.7.3.2/4 - 释放函数将使指向释放存储的所有部分的所有指针无效).
Suppose in C++ code I have a valid pointer and properly delete it. According to C++ standard, the pointer will become invalid (3.7.3.2/4 - the deallocation function will render invalid all pointers referring to all parts of deallocated storage).
至少在大多数实现中,它会保留该值,并将存储与 delete 之前完全相同的地址,但是 使用该值是未定义的行为.
At least in most implementations it preserves the value and will store exactly the same address as before delete, however using the value is undefined behavior.
标准是否保证指针将保留其值或允许值更改?
Does the standard guarantee that the pointer will preserve its value or is the value allowed to change?
推荐答案
不,不能保证,实现可以合法地将零分配给 lvalue 操作数以delete.
No, it's not guaranteed and an implementation may legitimately assign zero to an lvalue operand to delete.
Bjarne Stroustrup 曾希望实现会选择这样做,但不是很多.
Bjarne Stroustrup had hoped that implementations would choose to do this, but not many do.
http://www.stroustrup.com/bs_faq2.html#delete-zero
这篇关于指针是否保证在 C++ 中的“删除"之后保留其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:指针是否保证在 C++ 中的“删除"之后保留其值
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
