I had some problems converting a std::list<MyType>::iterator to MyType*. I have an array of MyType and as I loop through it, I call some void doSomething(const MyType* thing). Eventually I do this:
std::list<MyType> types = ... something here ...;
for( std::list<MyType>::const_iterator it = types.begin(), end = types.end(); it != end; ++it ) {
doSomething(&*it);
}
My question is, whether I do or do not create a memory copy of the MyType by this operation:
&*it
Trying to simply pass the iterator as if it was pointer, or to cast the iterator to pointer raised compiler errors.
No, the sequence of * and & does not create a copy:
* applied to an iterator produces a reference& applied to a reference produces the address of the originalNeither of these two steps requires copying of MyType's data.
Note: When the presence of an overloaded operator & is a possibility, it is safer to use std::address_of(*it) expression.
One of the requirements for an iterator is that it be derefernceable -- i.e. *it be supported. See http://en.cppreference.com/w/cpp/concept/Iterator. Whether *it returns a reference or a copy is not specified.
In theory, an implementation could return a copy when using *it.
In practice, most implementations return a reference when using *it. Hence, you most likely won't be seeing a copy being made when using &*it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With