Skip to main content
GameDev.net gamedev.net
🔒 Locked

question about the std::swap() function

Started by digitalfreak Dec 1, 2004 at 10:18 AM 1 replies 700+ views
Original Post
digitalfreak
digitalfreak
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?
Polymorphic OOP
Polymorphic OOP
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.
digitalfreak
digitalfreak
nice explaination. thanx
Mmm, Redmond Washington, Microsoft dude?

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.