Is there a way to declare an iterator which is a member variable in a class and that can be incremented using a member function even though the object of that class is const.
+7
A:
That would be with the "mutable" keyword.
class X
{
public:
bool GetFlag() const
{
m_accessCount++;
return m_flag;
}
private:
bool m_flag;
mutable int m_accessCount;
};
James Curran
2009-02-26 16:38:24
This will work for integers but if it is an iterator to a list or a map it doesnt work on const objects. It throws error at iter = list.begin() saying no "=" operator available.
2009-02-26 17:30:06
@tmpforspam: Without being able to see the complete error message you're getting, it sounds like "list" is also const and you should be using a const_iterator.
Shmoopty
2009-02-26 17:40:04
+5
A:
Are you sure you need iterator as a member? Iterators have an ability: they become invalid. It is a small sign of a design problem.
Mykola Golubyev
2009-02-26 17:00:31
I want to iterate through a list using a member functions. getFirst and getNext kind of....But for that I want to declare a mutable iterator so taht I can iterate on const objects.
2009-02-26 17:27:45
go for the STL-Design of iterators. It is accepted in the C++ comunity and would not suprise other developers. That would mean that the iterator is not part of the class.
Tobias Langner
2009-10-02 07:26:01
@tmpforspam: if the behavior of your object changes when calling your member function, it's not a const function.
xtofl
2009-10-02 08:19:51
A:
Got it.
using namespace std;
class tmptest
{
public:
void getNextItr()const
{
m_listItr = m_list.begin();
m_listItr++;
}
list<string> m_list;
mutable list<string>::const_iterator m_listItr;
};
Mutable along with const_iterator works... Thanks for reminding me mutable vs volatile. I got volatile confused with mutable. Thanks again!!!
This is a serious breach-of-contract: after calling the `getNextItr()` function, client code will assume the object is still the same, but it's not.
xtofl
2009-10-02 08:21:43
A:
this article explains both Mutable and Volatile: http://cpptalk.wordpress.com/2009/09/16/mutable-and-volatile/
rmn
2009-10-02 07:18:20