Reputation: 2662
The syntax of STL list::insert is as below -
iterator
insert(iterator __position, const value_type& __x);
Why a iterator instead of a reference to an iterator is being passed?
Upvotes: 2
Views: 355
Reputation: 137810
An implementation would be allowed to pass the iterator by const reference instead of by value. There is no relevant semantic difference.
Passing by value is slightly more efficient in this case. The iterator
object contains a single pointer to a list element object on the heap. Remember that passing by reference is essentially passing by pointer, behind the scenes. (Although a reference is not the same as a pointer, when crossing an actual function call boundary, there is no other viable implementation.)
So, passing by value means the pointer-to-heap gets passed, but passing by reference means the pointer-to-iterator
gets passed, and then two indirections are required inside the insert
function. (This does in theory depend on the ABI, but anyway there cannot be a disadvantage to pass by value.)
A quick illustration of passing semantics:
template< typename param >
void same_params( param a, param b ) {
std::cout << ( &a == &b ) << '\n';
}
int main() {
int const five = 5;
same_params< int const & >( five, five ); // true
same_params< int const & >( five, 6 ); // false
same_params< int const & >( five, 5 ); // unspecified
same_params< int const & >( 5, 5 ); // unspecified
same_params< int >( five, five ); // false (for any arguments)
}
If it weren't passing pointers, there is no way for same_params< int const & >
to work.
Upvotes: 1