为什么 C++删除运算符没有将指针设置为 NULL?

发布于 2024-09-26 00:06:09 字数 224 浏览 1 评论 0原文

可能的重复:
为什么删除不将指针设置为 NULL? < /p>

是指向已释放内存的指针有什么用途吗?

Possible Duplicate:
Why doesn't delete set the pointer to NULL?

Is there any purpose for a pointer to deallocated memory?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冰葑 2024-10-03 00:06:09

C++ 完全按照您的指示去做。您没有将指针设置为空,而是删除了指针指向的内存。

如果不需要,为什么要浪费将其设置为 null 的额外步骤(出于性能原因)?

C++ does exactly what you tell it to do. You didn't set the pointer to null, you deleted the memory that the pointer is pointing to.

Why would you waste the extra step of setting it to null (for performance reasons), if you didn't need to?

吖咩 2024-10-03 00:06:09

如果是 const 指针怎么办?

What if it's a const pointer?

べ繥欢鉨o。 2024-10-03 00:06:09

不,将其设置为原始值没有任何实际用处,除了显示人们在编写代码方面是多么无能:-)

它遵循 C 的传统,因为您应该知道自己在做什么。在 C 时代,让编译器将释放的指针设置为 NULL 的成本被认为太高,并且这种情况已通过 delete 转移到了 C++ 中。如果您编码正确,那么让编译器将指针设置为 NULL 是一种浪费,因为您要么将其设置为其他值,要么不再使用它。

如果你真的想让你的代码更安全,你会做类似的事情(用C语言):

void myFree (void **pMem) {
    free (**pMem);
    *pMem = NULL;
}
myFree (&x);

而不是仅仅:

free (x);

但是,如果你要达到那个级别(并引入这样一个令人厌恶的东西),只需切换到Java并完成它,那么您根本不必关心手动内存管理。

No, there's no real use to leaving it set to the original value, other than showing how inept people are at writing code :-)

It follows the traditions of C in that you're expected to know what you're doing. The cost of having the compiler set freed pointers to NULL was deemed too high in the C days and this has carried over to C++ with delete. If you code properly, then having the compiler set the pointer to NULL is a waste, since you'll either set it to something else or not use it again.

If you really want to make your code safer, you'd do something like (in C):

void myFree (void **pMem) {
    free (**pMem);
    *pMem = NULL;
}
myFree (&x);

instead of just:

free (x);

But, if you're going to go to that level (and introduce such an abomination), just switch to Java and be done with it, then you don't have to concern yourself with manual memory management at all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文