int* ptr = new int(0); delete ptr; //delete is allowed to modify ptr,for example set it to 0 std::cout << ptr; // UB?
确认(*),是否读取ptr(以打印的形式)定义良好?
解决方法
If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value,the deallocation function shall deallocate the storage referenced by the pointer,rendering invalid all pointers referring to any part of the deallocated storage.
Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.
有一个脚注:
Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.
这是从C11开始变化的,粗体字表示“未定义行为”,没有脚注.
所以要回答你的问题,删除ptr;被允许设置一个陷阱值,该值将导致std :: cout的运行时故障<< PTR.编译器文档必须指定行为.这是比UB更窄的限制,在这种情况下,任何不稳定的行为都是允许的.
原文地址:https://www.jb51.cc/c/116411.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。