为什么我不应该尝试使用

为什么我不应该尝试使用

本文介绍了为什么我不应该尝试使用“this” “删除此”之后的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这一段中,使用 delete this 构造。列出了4个限制。



限制1到3看起来相当合理。但为什么是限制4那里,我不能检查它,与另一个指针,比较它与NULL,打印,铸造,做任何事情与它?



我的意思是这个是另一个指针。为什么我不能 reinterpret_cast 它到 int 或调用 printf c $ c>以输出其值?

解决方案

在删除指针后不能做任何事情的原因,或任何其他指针),是硬件可能(和一些旧机器)捕获试图加载无效的存储器地址到寄存器。即使它在所有现代硬件上都可以正常工作,标准说,你可以对无效指针(未初始化或删除)做的唯一的事情是分配给它(NULL,或者从另一个有效的指针)。


In this paragraph of C++ FAQ usage of delete this construct is discussed. 4 restrictions are listed.

Restrictions 1 to 3 look quite reasonable. But why is restriction 4 there that I "must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it"?

I mean this is yet another pointer. Why can't I reinterpret_cast it to an int or call printf() to output its value?

解决方案

The reason that you cannot do anything with a pointer after you delete it (this, or any other pointer), is that the hardware could (and some older machines did) trap trying to load an invalid memory address into a register. Even though it may be fine on all modern hardware, the standard says that the only thing that you can do to a invalid pointer (uninitialized or deleted), is to assign to it (either NULL, or from another valid pointer).

这篇关于为什么我不应该尝试使用“this” “删除此”之后的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 12:22