在 C++ 中的析构函数中删除指针后将 NULL 分配给指针有什么用吗?
可能的重复:
是否值得在析构函数中将指针设置为 NULL?< /a>
我看到一些像这样的代码,
void ClassA::~ClassA()
{
delete member;
member = NULL;
}
因为在这个析构函数之后特定的实例不再存在(或者实例被破坏并且其成员不能再使用或取消引用),将 NULL 分配给成员变量指针?
这只是删除其他地方的指针并为其分配 NULL 的做法吗?
Possible Duplicate:
Is it worth setting pointers to NULL in a destructor?
I see some code like this,
void ClassA::~ClassA()
{
delete member;
member = NULL;
}
as the particular instance doesn't exist anymore after this destructor (or the instance is destructed and its members can't be used or dereferenced anymore), what is the use of assigning NULL to the pointer of member variable?
Is it just a practice taken from deleting a pointer elsewhere and assigning NULL to it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是毫无意义的 - 该空间在重新分配之前不会再次使用。
It's pretty pointless - the space isn't going to be used again until it is reallocated.
这对于发布代码毫无意义,但对于调试可能有帮助。
It's pointless for release code, but potentially helpful for debugging.
我认为没有理由更新已经超出范围的数据,并且“以防万一”做事并不是一个好的做法。
无论如何,不要盲目追随“良好实践”,了解自己为什么做事比成为“良好实践”宗教最热衷的实践者更好。
I see no reason for updating data which is already out of scope, and it is NOT good practice to do things "just in case".
At any rate do not follow "good practices" blindly, it is better to understand why you do things than being the most fervours practitioner of the "good practices" religion.
是的,这只是一个很好的做法。帮助人们不要忘记在其他地方将指针设置为 null ;)
yes, this is just good practice. helps one not to forget to set pointers to null elsewhere ;)