Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does &*x operation create a copy?

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.

like image 324
Tomáš Zato - Reinstate Monica Avatar asked Jul 24 '26 21:07

Tomáš Zato - Reinstate Monica


2 Answers

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 original

Neither 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.

like image 189
Sergey Kalinichenko Avatar answered Jul 27 '26 11:07

Sergey Kalinichenko


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.

like image 20
R Sahu Avatar answered Jul 27 '26 13:07

R Sahu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!