gpt4 book ai didi

c++ - 使用已删除的指针地址

转载 作者:可可西里 更新时间:2023-11-01 15:51:50 29 4
gpt4 key购买 nike

(*) 据我所知,标准允许实现修改 delete 运算符的操作数,但是大多数实现不这样做。

int* ptr = new int(0);
delete ptr; //delete is allowed to modify ptr, for example set it to 0
std::cout << ptr; // UB?

确认 (*),ptr 的读取(以打印的形式)是否定义明确?

如果delete确实修改了ptr,是否允许设置陷阱值,这会使读取ptr UB?

最佳答案

在 C++14 中,这是实现定义的行为,[basic.stc.dynamic.deallocation]/4:

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.

自 C++11 以来,这发生了变化,其中粗体文本表示“未定义的行为”并且没有脚注。


所以回答你的问题,delete ptr;允许设置一个陷阱值,该值会导致 std::cout << ptr 的运行时错误.编译器文档必须指定行为。这是一个比 UB 更窄的限制,在 UB 情况下,任何不稳定的行为都是允许的。

关于c++ - 使用已删除的指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43508771/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com