-1

Consider these two classes (List<Type> and List<Type>::iterator)

// List<Type>
template<typename Type>
class List {
public:
    class iterator;
    iterator& iter();

private:
    Type *elems; // Array
};

// List<type>::iterator
template<typename Type>
class List<Type>::iterator {
public:
    Type *current;
    Type operator* ();

private:
    iterator (Type *current) : current(current) {}
};

template<typename Type>
typename List<Type>::iterator& List<Type>::iter () {
    return (iterator(this->elems));
}

// Program
int main () {
    List<int> *list = new List<int>();
    List<int>::iterator iter = list->iter(); // When does iter get destroyed?
    delete list;
}

I read about this return with parentheses return (...); as a return-by-reference so to speak. I'm not sure, but I think iter is created on the stack (because of the absence of new). So my question is: When does iter go out of scope? After iter(), after main() or somewhere else? Do I have to delete it manually?

Cubi73
  • 1,891
  • 3
  • 31
  • 52

2 Answers2

1

You returned a reference to a temporary object, so it is destroyed before the caller even gets access to the reference (you have undefined behavior).

What (where) did you read about "return with parentheses"? So far as I understand, that makes an important difference when the compiler must deduce the return type. But you specified the return type, so those parentheses should make no difference. If you read something different from that, what did you read where?

On reread, I think you are confusing two different objects. The iterator created inside iter() is destroyed before main can see it. The iter defined in main is a different object. It starts as a copy of the first one (but copied after the first one was destroyed) and goes out of scope by the normal rules as a local variable of main

JSF
  • 5,281
  • 1
  • 13
  • 20
  • Now you cleared up my confusion :) To reference this parentheses-thingy, I skimmed this post (http://stackoverflow.com/questions/4762662) about "Significance of parentheses in a return statement". – Cubi73 Nov 14 '15 at 11:46
0

This code should not compile. You are returning a mutable reference to a temporary, which is illegal under the C++ Standard.

Even if it were a const ref, you are returning a reference to a local, which is undefined behaviour.

The parentheses around return mean nothing in this case.

Puppy
  • 144,682
  • 38
  • 256
  • 465