使用已删除的指针地址 [英] Use of a deleted pointer address

查看:72
本文介绍了使用已删除的指针地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(*) As far as I know the Standard allows an implementation to modify the operand of the delete operator, however most implementations do not do that.

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

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

Acknowledging (*), is the reading of ptr (in the form of printing it) well-defined?

如果 delete 确实修改了 ptr ,是否可以设置陷阱值,从而使读取 ptr UB成为可能?

If delete does modify ptr, is it allowed to set a trap value, which would make reading ptr UB?

推荐答案

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

In C++14 this is implementation-defined behaviour, [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起,这种情况发生了变化,其中粗体字显示为未定义的行为",并且没有脚注.

This changed since C++11 where the bolded text said "undefined behaviour" and there was no footnote.

为回答您的问题,允许 delete ptr; 设置一个陷阱值,该值将导致 std :: cout<<ptr .编译器文档必须指定行为.与UB相比,这是一个较窄的限制,在这种情况下,任何不稳定的行为都是允许的.

So to answer your question, delete ptr; is allowed to set a trap value that would cause a runtime fault for std::cout << ptr. The compiler documentation must specify the behaviour. This is a narrower restriction than UB in which case any unstable behaviour would be permissible.

这篇关于使用已删除的指针地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆