Sign in to follow this  
digitalfreak

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 this post


Link to post
Share on other sites
Quote:
Original post by digitalfreak
on 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 this post


Link to post
Share on other sites

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

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this