V
Victor Bazarov
Roel said:The following will not compile under gcc 3.2.2:
#include <string>
#include <vector>
#include <iostream>
#include <ctype.h>
class A
{
public:
int a;
};
int main(int argc, char* argv[])
{
A a1, a2, a3;
std::vector<A> alist;
alist.push_back(a1);
alist.push_back(a2);
alist.push_back(a3);
for (int i = 0 ; i < alist.size() ; i++) {
A* pntr = const_cast<A*>(alist.begin() + i);
What's this ugliness for?
A* pntr = & alist;
std::cout << pntr->a << std::endl;
And why do you need a pointer anyway? Why not just write
std::cout << alist.a << std::end;
???
}
return 0;
}
The error message is
test.cpp: In function `int main(int, char**)':
test.cpp:22: invalid const_cast from type `__gnu_cxx::__normal_iterator<A*,
std::vector<A, std::allocator<A> > >' to type `A*'
But when I change the const_cast line to
A* pntr = const_cast<A*>(&(*(alist.begin() + i)));
it will work as expected (note the extra dereference and address-of
operator). But this obviously looks ugly - what is the correct way to do
this? Isn't the first form supposed to convert to an A* directly? Thanks.
No, it's not. An iterator is an iterator. It is its own type, not
a constant pointer. And it doesn't have to be convertible to a pointer
(contrary to what some might want to believe).
Victor