template<class T> void swap(T&a, T&b)
{
T tmp = a;
a = b;
b = tmp;
}
question about the std::swap() function
on the C++ Programming Language (special edition) page 538 define the function as
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?
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.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement