简体   繁体   中英

Implementation of swap function for deque with constant complexity

It is said that the std::deque swap function takes constant time,not linear. http://www.cplusplus.com/reference/deque/deque/swap-free/ . How is that function implemented then?

All resizable standard library containers (that is, all except std::array ) have to store their contents in dynamically allocated memory. That is because they can grow arbitrarily large and there's no way to store arbitrarily many objects in the fixed space occupied by the container object itself. In other words, it must be possible that container.size() > sizeof(container) .

This means that the container object only stores a pointer to its contents, not the contents itself. Swapping two containers therefore means simply swapping these pointers. In extremely simplified form:

template <class T>
class Container
{
  T *_begin, *_end;

  friend void swap(Container &a, Container &b)
  {
    std::swap(a._begin, b._begin);
    std::swap(a._end, b._end);
  }
};

Of course, in practice, this is complicated by the presence of allocators etc., but the principle is the same.

The implementation of deque is typically hidden by using pimpl idiom (each deque holds a pointer to implementation). The pointers are then swapped. It might (also) be that the deque at least holds a pointer to its buffer, which is then swapped (with related members like size).

This post (copy and swap idiom) is related to how the swap might be implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM