# question about the std::swap() function

This topic is 4831 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

on the C++ Programming Language (special edition) page 538 define the function as
template<class T> void swap(T&a, T&b)
{
T tmp = a;
a = b;
b = tmp;
}


but on page 98 it says "...the value of a reference cannot be changed after initializtion; it always refers to the object it was initialized to denote." aren't these contradictory?

##### Share on other sites
Quote:
 Original post by digitalfreakon the C++ Programming Language (special edition) page 538 define the function as*** Source Snippet Removed ***but on page 98 it says "...the value of a reference cannot be changed after initializtion; it always refers to the object it was initialized to denote."aren't these contradictory?

No. The quote you posted means that is not possible in standard C++ to change what the references are refering to. The swap function swaps the values of the objects that the references refer to, it does not swap what they refer to.

In other words, if "a_ref" refers to "a" which has the value 4 and "b_ref" refers to "b" which has the value 5, then after a swap, "a_ref" still refers to "a" however "a's" value is now 5 (the old value of b), and as well, "b_ref" still refers to "b" however "b's" value is now 4 (the old value of a).

The quote you posted means that once you initialize "a_ref" to refer to "a," you can never change it to refer to "b" or any other variable/object.

##### Share on other sites
nice explaination. thanx
Mmm, Redmond Washington, Microsoft dude?