Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a collection with 'const_iterator' in a function declared 'const' results in an error

This method:

void LRU::displayQueue() const
{
   for(iter = m_buffer.begin(); iter != m_buffer.end(); ++iter)
      std::cout << (*iter) << " ";
   std:: cout << std::endl;
}

results in the following error:

lru.cpp:58: error: passing 'const std::_Deque_iterator<int, const int&, const int*>' as    'this' argument of 'std::_Deque_iterator<int, const int&, const int*>& std::_Deque_iterator<int, const int&, const int*>::operator=(const std::_Deque_iterator<int, const int&, const int*>&)' discards qualifiers

m_buffer and iter are declared in my header file, where the buffer is declared as a deque of type int and iter is a constant iterator:

// ...

std::deque<int> m_buffer;
std::deque<int>::const_iterator iter;

// ...

Removing the const in the displayQueue method will eliminate the compiler error, but since this function shouldn't modify any data in the deque, I want to make this explicit by keeping my code "const-correct". Why would this result in an error, when my iterator is a const_iterator?

like image 607
dtg Avatar asked Nov 17 '25 14:11

dtg


1 Answers

You cannot modify any members of a class in a const member method, and that's what you're trying to do here:

for(iter = m_buffer.begin();iter != m_buffer.end(); ++iter)
    ^^^^^^^                                         ^^^^^^

iter is a member of class LRU, so you can't assign, increment or otherwise change it in a const member function.

One solution would be to make iter mutable:

mutable std::deque<int>::const_iterator iter;

But my feeling is most uses of mutable are an indication of a design flaw. In this case, I'd suspect that having iter be a member of class LRU in the first place is a potential design flaw. Why would you need/want this?

So, instead of making iter a mutable member, I'd first consider not having it be a member at all and use a local variable instead.

like image 95
John Dibling Avatar answered Nov 19 '25 05:11

John Dibling