问题
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.
回答1:
The error is clear enough -
error: reference to local variable 'temp' returned
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, instead
template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {
you maybe need
// note the missing `&`...............vv
template <typename T> btree_iterator<T> btree_iterator<T>::operator++(int) {
回答2:
You are returning a reference to a temporary variable. Change your declaration as:
template <typename T> btree_iterator<T> btree_iterator<T>::operator++(int);
来源:https://stackoverflow.com/questions/7846221/c-post-increment-operator-overload-in-iterators-compiling-with-wall-werror