我最近了解到所有stl容器都有swap函数: 即
c1.swap(c2);
将导致对象底层c1被分配给c2,反之亦然。 我问过我的教授,如果c1和c2是引用,情况是否也是如此。 他说是遵循相同的机制。
我想知道它是如何发生的,因为c ++引用无法重置。
答案 0 :(得分:4)
引用是别名。如果你有两个引用,调用swap将交换它们引用的内容,而不是引用本身。
C& r1 = c1; // r1 references c1
C& r2 = c2; // r2 references c2
r1.swap(r2); // same as c1.swap(c2)
并且它不是被交换的变量,而是它们在逻辑上独立而被交换的原因。如果容器只包含指针,如果将该指针与另一个容器的指针交换,则有效交换容器。变量本身仍然存在。
具体例子:
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
答案 1 :(得分:1)
这是被交换的容器的内容,即c1
的元素被移动到c2
,反之亦然。玩具实现可能看起来像这样:
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;
};