mihai
mihai

Reputation: 4742

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).

Upvotes: 1

Views: 1227

Answers (3)

Daniel Frey
Daniel Frey

Reputation: 56883

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.

Upvotes: 2

user2249683
user2249683

Reputation:

Do not do it: If you want to have semantics like first(), next(), last() for iterating a container, create a proxy:

Proxy iteration() const { return Proxy(*this); }

Upvotes: 0

Ivan Ishchenko
Ivan Ishchenko

Reputation: 1526

If you have a member you wish to modify at const methods - declare them mutable.

Upvotes: 1

Related Questions