views:

164

answers:

2

I recently learned that all stl containers have swap function: i.e.

c1.swap(c2);  

will lead to object underlying c1 being assigned to c2 and vice versa. I asked my professor if same is true in case of c1 and c2 being references. he said same mechanism is followed.

I wonder how it happens since c++ references cannot be reseted.

+1  A: 

It's the content of the containers that's being swapped, i.e. the elements of c1 are moved to c2 and vice versa. A toy implementation could look something like this:

template <class T>
class vector {
    void swap(vector& other) {
        swap(other.m_elements, m_elements);
        swap(other.m_size, m_size):
    }
    T* m_elements;
    size_t m_size;
};
Andreas Brinck
+3  A: 

References are aliases. If you have two references, calling swap will swap what they are referring to, not the references themselves.

C& r1 = c1; // r1 references c1
C& r2 = c2; // r2 references c2

r1.swap(r2); // same as c1.swap(c2)

And it's not the variables that get swapped, it's what make them logically independent that gets swapped. If a container only consists of a pointer, if you swap that pointer with the pointer of another container, you've effectively swapped the containers. The variables themselves remain.


Concrete example:

typedef std::vector<int> vec;

vec c1;
vec c2;

// fill em up

c1.swap(c2);
/*
A vector, internally, has a pointer to a chunk of memory (and some other stuff).
swap() is going to swap the internal pointer (and other stuff) with the other
container. They are logically swapped.
*/

vec& r1 = c1; // r1 is an alias for c1
vec& r2 = c2; // r2 is an alias for c2

r1.swap(r2); // same as c1.swap(c2). they are now unswapped
GMan
ok so if the c1 points to a say pair, then the pointer inside the pair object are now changed.
sm1
@sm1: What do you mean points to? Let me edit to give a concrete example so we can clear up some confusion.
GMan