A problem with non const iterators that behave like const ones
Hello.
I'm facing a strange issue. I'm using composed types (like std::map(s)
of std::set(s)) and everything works fine, but when I try to access
structures stored in these variables to modify them, the gcc
compiler(s) (from gcc 3.2 to gcc 4.x) refuse to compile it while msvc
does.
Here's an easy snippet:
---------------------------------------------------------
#include <map>
#include <set>
#include <vector>
class Foo
{
struct Bar
{
unsigned int a;
long b;
std::vector<char> c;
Bar(const unsigned int& _a) : a(_a), b(0)
{
}
friend bool operator<(const Bar& lhs, const Bar& rhs)
{
return lhs.a < rhs.a;
}
};
typedef std::set<Bar> SET_BAR;
typedef std::map<unsigned int, SET_BAR> MAP_UBAR;
MAP_UBAR _mapUbar;
public:
static Foo& Instance(void)
{
static Foo _foo;
return _foo;
}
void DoesntCompile(const unsigned int& idx, const unsigned int& x,
const long& y, const std::vector<char>& z);
};
void Foo::DoesntCompile(const unsigned int& idx, const unsigned int&
x, const long& y, const std::vector<char>& z)
{
MAP_UBAR::iterator itMap = _mapUbar.find(idx);
if (itMap != _mapUbar.end())
{
SET_BAR::iterator itRes = itMap->second.find(x);
if (itRes != itMap->second.end())
{
itRes->b = y;
itRes->c = z;
}
}
}
int main(int argc, char *argv[])
{
}
--------------------------------------------------------
and here the error(s)
--------------------------------------------------------
Foo.cpp: In member function `void Foo::DoesntCompile(const unsigned
int&, const
unsigned int&, const long int&, const std::vector<char,
std::allocator<char>
>&)':
Foo.cpp:45: assignment of data-member `Foo::Bar::b' in read-only
structure
Foo.cpp:46: passing `const std::vector<char, std::allocator<char> >'
as `this'
argument of `std::vector<_Tp, _Alloc>& std::vector<_Tp,
_Alloc>::operator=(const std::vector<_Tp, _Alloc>&) [with _Tp =
char, _Alloc
= std::allocator<char>]' discards qualifiers
--------------------------------------------------------
I really don't understand why the compiler thinks that data member
Foo::Bar::b is in read only structure when I'm using ::iterator and
not ::const_iterator.
Do you have any suggestions? Until now to solve this issue in gcc
platform I just used a raw pointer with brute cast.
Thanks in advance,
Emanuele.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]