Home > Enterprise >  Why is the iterator destructor implicitly called?
Why is the iterator destructor implicitly called?

Time:08-12

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?

CodePudding user response:

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;

CodePudding user response:

The expression itr results in 2 values: the old value (which is going to be used in the expression) and the incremented value (which is going to be in itr after the rhs of the expression is evaluated, as a side effect). When you use (itr )->value, the old value is expected to be alive till ; and then destructed.

If you'd like not to have a destructor there, suggest using int first_value itr->value; itr;. Or - even better - if you can reformulate your code, use ( itr), i.e., prefix increment.

  • Related