Boost logo

Boost Users :

From: nicola (vitacolo_at_[hidden])
Date: 2008-01-12 13:21:36


In article <478810E0.7030407_at_[hidden]>,
 Steven Watanabe <watanabesj_at_[hidden]> wrote:

> AMDG
>
> nicola wrote:
> > Hi,
> > I have a class modeling a record-based read-only binary file and I have
> > written a random access iterator based on iterator_facade to iterate
> > over the records. The class looks like this:
> >
> > class my_binary_file {
> >
> > <snip>
> >
> > explicit my_binary_file_iterator(my_binary_file* ff, unsigned int n)
> > : ff_ptr_(ff), rec_num_(n) { }
> >
>
> my_binary_file* is *not* const here.

Thanks for pointing that out. In the tutorial example at
 
http://www.boost.org/libs/iterator/doc/iterator_facade.html#tutorial-exam
ple

sect. "A constant node_iterator", shouldn't the constructor's parameter
of const_node_iterator be const? That is,

explicit const_node_iterator(const /* <== ? */ node_base* p)
      : m_node(p) {}

> >
> > <snip>
> >
> > };
> >
> > public:
> > typedef my_binary_file_iterator iterator;
> >
> > iterator begin() *const* { return iterator(this, 0); }
> >
>
> this is a pointer to const. The constructor of iterator requires a
> pointer to non-const.

There is more than that, however: as you can see in my original post,
get_record() and seekg() are not const and that is a problem
because they are invoked by dereference(). I can compile successfully if
I const-qualify them, but this is not correct in my opinion.
The fact is, they do change the state of the object in a visible way.
That's the implementation of get_record() that I had omitted in the
original post (but that you could have easily guessed):

   bool get_record(key_type& k, value_type& v) /* const ??? */ {
      if (fs_.read(reinterpret_cast<char*>(&k), key_size_)) {
         if (fs_.read(reinterpret_cast<char*>(&v), sizeof(value_type))) {
            return true;
         }
      }
      return false;
   }
So, for example, calling get_record() twice results in two consecutive
records to be read — not the same record. Moreover, I will be
interested, at a later stage, in extending the class so that it can read
and *write* files.

Is there any better solution than using const member functions for my
get_record() and seekg()?

Nicola


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net