Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

auto-initializing and const correctness

Tags:

c++

I have a custom iterator implementation (it iterates over a db query result, but that is irrelevant to this). It conceptually has 2 sets of functions: get type functions, which return a value from the current item (current row), and setup type functions (in my case binds), which set up the iterator before it starts the iteration, so a new iterator instance is actually not pointing to the first item yet. There is also a reset function that nullifies the iterator and readys for being setup differently.

When one of the get functions is called, it first checks if the iterator is still new or has been reset (effectively pointing to begin()-1) and if so, advances it to the first item. The get functions would (should) be const, except that that conditional first advancement prevents this.

Should I:

  1. Declare them const and throw in a mutable for the isReset flag, or
  2. Leave it as is, and accept the fact that under-the-hood initializing the object makes it non-const, or
  3. Replace the self-initializing with a check for initialized state, and leave it up to the user to call operator++ once before calling any of the get functions?
like image 832
Baruch Avatar asked Dec 02 '25 09:12

Baruch


1 Answers

Your iterator has state (i.e. whether or not underlying data is available yet), and the "get" function alters that state. So that makes it just like any other iterator. The "get" function shouldn't be const. By the way, instead of calling your function "get", it would be better to make the iterator have the same interface as Standard Library iterators - then you can use standard algorithms on it. So use the operator*() and operator++() functions among others.

like image 91
Klitos Kyriacou Avatar answered Dec 04 '25 22:12

Klitos Kyriacou