本文发表在 rolia.net 枫下论坛First, it is different to swap two pointers vector * a, *b;
and two vectors vector a, b
The former doesn't change the two vector objects pointed to by a and b, it just changes the pointers, while the latter swaps the contents of the two vectors. what if users really need to do the latter?
Second, the member function vector::swap(vector&) can be done in constant time, because it only swaps some member variables of primitive types, usually just pointers to the start, finish and end_of_storage of the memory block allocated for vector, or/and counter.
As a result, if you have two vectors a and b, and you want to assign b to a efficiently, and you don't need b anymore, then swap is a lot faster than operator=, which (probably) needs to allocate memory ( if b is bigger than a), construct every object from b to the new memory location, then destroy everything in old a.
Last, since swap primitive types, say pointers, integers etc, never throws, swap is exception-safe. when you assign b to a, you create a temporary copy of b first, say c, if it succeeds, then you know you can swap c and a and there will be no exception thrown. If construction of c fails, then a is not affected, therefore safe.更多精彩文章及讨论,请光临枫下论坛 rolia.net
and two vectors vector a, b
The former doesn't change the two vector objects pointed to by a and b, it just changes the pointers, while the latter swaps the contents of the two vectors. what if users really need to do the latter?
Second, the member function vector::swap(vector&) can be done in constant time, because it only swaps some member variables of primitive types, usually just pointers to the start, finish and end_of_storage of the memory block allocated for vector, or/and counter.
As a result, if you have two vectors a and b, and you want to assign b to a efficiently, and you don't need b anymore, then swap is a lot faster than operator=, which (probably) needs to allocate memory ( if b is bigger than a), construct every object from b to the new memory location, then destroy everything in old a.
Last, since swap primitive types, say pointers, integers etc, never throws, swap is exception-safe. when you assign b to a, you create a temporary copy of b first, say c, if it succeeds, then you know you can swap c and a and there will be no exception thrown. If construction of c fails, then a is not affected, therefore safe.更多精彩文章及讨论,请光临枫下论坛 rolia.net