3

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.

Mick
  • 665
  • 2
  • 6
  • 18

2 Answers2

6

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) {
Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
  • Ah.... thanks so much Kiril... it's so very obvious now that you pointed it out. You're right, even the examples I found did it that way, I just didn't notice the difference. Regards! – Mick Oct 21 '11 at 07:28
  • 1
    @Mick: The compiler is trying it's best to help you with the error messages, try to understand what it is telling you. Part of the job is understanding error messages to know what is wrong or at least how the compiler is interpreting your code. – David Rodríguez - dribeas Oct 21 '11 at 07:40
  • @DavidRodríguez-dribeas Thanks David, definitely. Most the time I am able to figure out what the compiler is saying, but for some reason on this occasion I must have confused myself, and just couldn't see past the obvious. I'm actually quite embarrassed about that :-) – Mick Oct 21 '11 at 07:52
3

You are returning a reference to a temporary variable. Change your declaration as:

template <typename T> btree_iterator<T> btree_iterator<T>::operator++(int);
Paul Manta
  • 30,618
  • 31
  • 128
  • 208
Tio Pepe
  • 3,071
  • 1
  • 17
  • 22