本文发表在 rolia.net 枫下论坛1) a very easy one, method swap has the following signature
void swap(vector&); it's to swap the contents of two vectors, not to swap two elements
Can you provide pseudo-code for swap?
2) your insert method has a few problems,
a correct sequence of action ( suppose there is avaialbe space in vector) is like following
_Construct(_M_finish, *(_M_finish - 1));
++_M_finish;
_Tp __x_copy = __x;
copy_backward(__position, iterator(_M_finish - 2), iterator(_M_finish- 1));
*__position = __x_copy;
a) the first step is to construct a new object at the current end with placement new, if it succeeds, then increase the counter, otherwise if there is an exception, it will throw and the internal status of the vector is unchanged, thus exception-safe.
you CANNOT call memcpy instead of constructing simply because wherever the current end is, there should be no constructed object there ( if there was one there before, when pop_back is called, you should call destructor explicitly to destroy the ojbect at that location, and decrease the counter), therefore you have to call constructor to do the job. Plus, you CANNOT assume constructor does the same thing as bitwise memory copy in this situation
b) you CANNOT use memcpy to right shift the objects whose indices are bigger than the insert position, for the same reason as above. Instead, operator=() should be called to do the work. operator=() is NOT always bitwise copy.
If you read STL source code ( a little gibberish), you'll see that it's very smart. It uses template partial specialization and type traits to dispatch/optimize the code.
Simply speaking, it checks whether type T has trivial assignment operator=, if yes, it 'll use memmove to shift the objects, which is faster than memcpy. If no, then it will use a loop to call assignment operator= .
By default, the template traits has NO trivial assignment operator. However, it defines traits for builtin type like int, double etc to have trivial assignment operator so that those types can be optimized to memmove. So if you want to use memmove to optimize copy for your own type T, suppose operator= does the same thing as memcpy, then you can define traits for T
I don't know others, but to me it's a lot more difficult to write your own container (bug free, scalable and efficient in size and speed) than it seems, especially considering exception-safe. I hate to be a C++ programmer, LOL.更多精彩文章及讨论,请光临枫下论坛 rolia.net