Does std::vector call the swap function when growing? Always or only for some types?

c++, swap, vector

Solution

I have no links to back up this claims, but as far as I know, the STL implementation distributed with Microsoft C++ uses some internal non-standard magic annotations to mark `vector` (and other STL collections) as having-performant-swap so `vector<vector<>>` won't copy the inner vectors but swap them. Up to VC9 that is, in VC10 they'll switch to rvalue-references. I think you are not supposed to be able to mark your own classes the same way as there's no cross-compiler way to do it and your code will work only on the specific compiler version.

Edit: I had a quick look at the `<vector>` header in VC9 and found this:

    // vector implements a performant swap
template <class _Ty, class _Ax>
    class _Move_operation_category<vector<_Ty, _Ax> >
    {
    public:
        typedef _Swap_move_tag _Move_cat;
    };

Just for experiment, you could try to specialize this class for you own type, but as I said, this is STL version specific and it's going away in VC10

Problem

As far as I know I can use a vector of vectors (`std::vector< std::vector<int> >`) and this will be quite efficient, because internally the elements will not be copied, but swapped, which is much faster, because does not include copying of the memory buffers. Am I right? When does `std::vector` exactly make use of the swap function? I can't find anything about it in the C++ standard. Does it happen during buffer reallocation? I did some tests to find it out, but I failed. The swap function for my custom data type isn't called at all. EDIT: Here is my test program.

Original source

Related problems