使删除的指针失效?(Invalidating deleted pointers?)

编程入门 行业动态 更新时间:2024-10-08 23:01:38
使删除的指针失效?(Invalidating deleted pointers?) template<typename T> someclass<T>& operator=(const someclass<T>& other) { typename std::vector<T *>::const_iterator rhs; typename std::vector<T *>::iterator lhs; //identity test //this->data is std::vector<T *> for(lhs = this->data.begin(); lhs != this->data.end(); lhs++) { delete *lhs; } this->data.clear(); // this is what I forgot this->data.reserve(other.data.size()); for (rhs = other.data.begin(); rhs != other.data.end(); rhs++) { if (NULL == *rhs) { this->data.push_back(NULL); } else { this->data.push_back(new T(**rhs)); } } }

正如你在评论中看到的那样,我忘了清除数组中的旧指针。 当我第二次调用赋值运算符时,我得到glibc错误抱怨double free。 唯一提供的信息是被删除的地址。

这让我想到如何处理这类已删除的指针 - 当你不想再次删除它们,并且当你这样做时,它肯定是一个错误。 你不能将它们设置为NULL,因为另一个删除将是正确的。 您不想保留该值,因为可以将内存位置分配给新创建的对象。

调试的好处是有些值,比如INVALID,你给这些指针指定了“对这个指针调用delete是一个错误”,而不是NULL,它表示“在这个指针上调用delete就什么都不做”。 有没有这样的事情?

template<typename T> someclass<T>& operator=(const someclass<T>& other) { typename std::vector<T *>::const_iterator rhs; typename std::vector<T *>::iterator lhs; //identity test //this->data is std::vector<T *> for(lhs = this->data.begin(); lhs != this->data.end(); lhs++) { delete *lhs; } this->data.clear(); // this is what I forgot this->data.reserve(other.data.size()); for (rhs = other.data.begin(); rhs != other.data.end(); rhs++) { if (NULL == *rhs) { this->data.push_back(NULL); } else { this->data.push_back(new T(**rhs)); } } }

As you can see in the comments, I forgot to clear out the old pointers in the array. When I invoked the assignment operator for the second time, I got glibc error complaining about double free. The only information provided was the deleted address.

This make me thinking about what to do with such class of deleted pointers - when you don't want to delete them again, and when you do, it is certainly an error. You cannot set them to NULL, because another delete would be correct then. You don't want to keep the value as the memory location can be assigned to newly created object.

What would be good for debugging is some value, like INVALID, which you assign to these pointers saying "invoking delete on this pointer is an error", instead of NULL, which say "invoking delete on this pointer does nothing". Is there something like this?

最满意答案

解决此问题的方法是编写不包含任何删除的代码。 尽可能使用shared_ptr 。 当你拥有一个拥有多态对象的容器时,你也可以使用指针容器 。

The solution to this problem is to write code that does not contain any deletes. Use shared_ptr where possible. When you have a container that owns polymorphic objects, you can also use Pointer Container.

更多推荐

本文发布于:2023-08-07 11:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   Invalidating   pointers   deleted

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!