C++迭代器中的后递增运算符重载(使用 -Wall -Werror 编译)
我目前正在为 b 树创建自己的迭代器,并且我一直致力于如何在编译器不抱怨的情况下实现后递增运算符。
错误消息如下,并且是预期的(因为我正在按照错误消息所述进行操作)
cc1plus: warnings being treated as errors
error: reference to local variable 'temp' returned
我需要使用 -Wall 和 -Werror 标签编写函数,所以希望有人能够帮助我找到解决方案那。
这是函数:
template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {
btree_iterator<T> temp(*this);
pointee_ = pointee_->nextNode();
return temp;
}
我环顾四周,只能找到人们按照我目前的方式实现操作符的示例。
每当我以前遇到这样的问题时,我都会“更新”要返回的对象,这样它就不再是临时的了。但由于这是一个迭代器,如果我这样做,我将无法在之后释放内存,从而出现内存泄漏。
如果有人能够帮助我,我将不胜感激!如果我的设计还有任何其他内容可以帮助您理解问题,请告诉我。
问候。
I'm currently creating my own iterator for a b-tree, and I'm stuck on how to implement the post-increment operator without the compiler complaining.
The error message is as follows, and is expected (since I am doing exactly what the error message says)
cc1plus: warnings being treated as errors
error: reference to local variable 'temp' returned
I am required to write the function with the -Wall and -Werror tags, so hopefully someone is able to help me with a solution around that.
Here is the function:
template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {
btree_iterator<T> temp(*this);
pointee_ = pointee_->nextNode();
return temp;
}
I had a look around, and I was only able to find examples of people implementing the operator exactly how I am at the moment.
Whenever I previously had a problem like this, I 'new'ed the object I was returning so that it wasn't temporary any more. But since this is an iterator, if I did that, i won't be able to free the memory afterwards, and thus having memory leaks.
If anyone is able to help me out, that would be greatly appreciated! Please let me know if there is anything else about my design that would help you understand the problem.
Regards.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
错误非常清楚 -
在您的函数中,您返回对
temp
的引用,它是临时对象。也许您需要返回一个副本(因为您不想使用
new
)。所以,你可能需要
The error is clear enough -
In your function, you return reference to
temp
, which is temporary object.Maybe you need to return a copy(as you don't want to use
new
). So, insteadyou maybe need
您正在返回对临时变量的引用。将您的声明更改为:
You are returning a reference to a temporary variable. Change your declaration as: