question about the std::swap() function

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?

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

• Partner Spotlight

• Forum Statistics

• Total Topics
627689
• Total Posts
2978648

• 13
• 14
• 12
• 10
• 12