Search code examples
c++vectorpass-by-const-reference

How to modify/update the internal state of an object passed by const reference


Passing an object by const reference means we can't modify any of it's members. But suppose the object contains a vector<string> member. How do we write const methods to read the contents of the vector<string> member assuming that a vector<string>::iterator member is also needed and must be updated after every read to point to the next element in the vector?

Is this possible, or is there another method in this situation? That is, don't modify the contents of the passed by const reference object, but the object should be able to update it's internal state (i.e. next element in the vector to be read).


Solution

  • It sounds like you are looking for the keyword mutable. A mutable member variable is modifyable within a const member method. You can read about it here. An example:

    class A
    {
        std::vector< int > v_;
        mutable std::vector< int >::const_iterator current_;
    
    public:
        int get() const // note the const
        {
            assert( !v_.empty() );
            if( current_ == v_.end() ) current_ = v_.begin();
            return *current_++;
        }
    };
    

    Note you still need const_iterator as the vector itself is const and hence v_.begin() does not give you a normal iterator. You could fix this by marking the vector itself also as mutable, then you could use iterator.

    Here's a complete live example.