Search code examples
c++iterator

Why is the iterator destructor implicitly called?


I'm creating an Iterator interface for my foo class, but while debugging, the iterator's destructor is being implicitly called after the first test.

// Setup for test

// First test
foo::Iterator itr = obj->begin();
int first_value = (itr++)->value; // Destructor called here

// Other tests with itr

I've gone through the call stack and noticed that every other call in this line is working as expected. The only problem seems to be that once every other call in the line is executed (postfix increment and arrow operator) the destructor is being implicitly called. Why is this happening?


Solution

  • postfix increment

    Why do you think everyone tells you not to use it? A postfix increment is a prefix increment with an additional copy that has to get constructed and then destroyed for no reason.

    This is correct code:

    foo::Iterator itr = obj->begin();
    int first_value = itr->value; 
    ++itr;