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更窄的限制,在这种情况下,任何不稳定的行为都是允许的.