I have an iterator and I want to return a pointer to the element it is pointing to.
Is this ok to do?
return &*iter;
It doesn’t really seem like a good idea.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is perfectly fine. But be aware that if the iterator is of a container which deallocates and reallocates memory on resizing, then the returned pointer will become invalid. For example, if the iterator is an iterator of
std::vector, theniterand&*iterboth become invalid if the underlying vector resizes itself.By the way, the title of the topic and what you said in the very first line, do not match:
Both of these mean different. What you have written, i.e
return &*iteris what you said in the title. But second statement means this:It returns the element the iterator is syntactically pointing to. It does not return the pointer to the element. This is safe even if the vector resizes itself.