字体:
Interesting question, I was thinking about it too :-) [#2875519@0 -ROLIA.NET 相约加拿大网上社区 之 枫下论坛 & 枫下部落, 枫下论坛主坛 ]

Interesting question, I was thinking about it too :-)

by super_unknown (mailman) at 2006.3.31 01:21 (#2875519@0)
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.

该话题已在历史区内,不能被修改或回复。       收藏    投诉
关闭窗口