问题
It occurred to me that the fastest way to copy the array from one std::vector
to another would be to swap their pointers, as long as you don't care anymore about the vector you are swapping from. So I went looking and found std::vector::swap
. I assume that swapping pointers is how its implemented, but I didn't see an explanation in the reference.
回答1:
A simplified, minimal vector implementation might have something like the following members to manage the data in the vector:
template <typename T>
class simple_vector
{
public:
// ...
static
void swap(simple_vector<T>& x, simple_vector<T>& y);
private:
T* elements; // a pointer to the block of memory holding the elements in the vector
size_t count; // number of 'active' elements
size_t allocated; // number of elements allocated (not all of which are necessarily used at the moment)
};
A swap()
operation would just swap the 'guts' of each simplified_vector, leaving all of the dynamically allocated buffers (and the elements contained in them) in place. Only the pointers to those dynamic allocations get move around:
template <typename T>
void simple_vector<T>::swap(simple_vector<T>& x, simple_vector<T>& y)
{
T* tmp_elements = x.elements;
size_t tmp_count = x.count;
size_t tmp_allocated = x.allocated;
x.elements = y.elements;
x.count = y.count;
x.allocated = y.allocated;
y.elements = tmp_elements;
y.count = tmp_count;
y.allocated = tmp_allocated;
}
Note that the actual std::vector
implementation might use techniques that aren't exactly the same (such as move constructing a temporary) as this simple example, but I think it conveys the general concept.
回答2:
From http://en.cppreference.com/w/cpp/container/vector/swap:
Exchanges the contents of the container with those of other. Does not invoke any move, copy, or swap operations on individual elements.
That seems clear enough to me.
Update, in response to comment by OP
I see the following with g++ 4.8.4:
void
swap(vector& __x)
#if __cplusplus >= 201103L
noexcept(_Alloc_traits::_S_nothrow_swap())
#endif
{
this->_M_impl._M_swap_data(__x._M_impl);
Alloc_traits::_S_on_swap(_M_get_Tp_allocator(),
__x._M_get_Tp_allocator());
}
And, here's the implementation of _Vector_impl::M_swap_data
:
void _M_swap_data(_Vector_impl& __x)
{
std::swap(_M_start, __x._M_start);
std::swap(_M_finish, __x._M_finish);
std::swap(_M_end_of_storage, __x._M_end_of_storage);
}
来源:https://stackoverflow.com/questions/35679165/how-is-stdvectorswap-implemented