I'm learning to use C++11 stuff, and ran into a situation where I'm not sure how to use auto
. Consider:
struct MyClass { double x; }
std::vector<MyClass*> myvec;
function_that_fills_vector(myvec);
//(1) this should be valid:
for(auto* item : myvec){ std::cout<< item->x <<std::endl; }
//(2) what about this?
for(auto item : myvec){ std::cout<< item.x <<std::endl; }
//(3) or this?
for(auto item : myvec){ std::cout<< item->x <<std::endl; }
That is, if I know my auto
is really a pointer, I can be explicit about it in the constructor, so I know the dereference operator is the right one. But if I change myvec
to hold objects, (1) will not compile anymore.
In (2) and (3) the underlying pointer nature is left implicit. Which member access operator (.
or ->
) is correct? If both work, is there a good reason to use one or the other? Will both continue to work if I change myvec
to be a vector<MyClass>
?