C++ Logo

std-proposals

Advanced search

item_traits: A simple solution for destructive move

From: Rick de Water <rick_water_at_[hidden]>
Date: Mon, 3 May 2021 09:22:06 +0000
When working on a container library I needed to manage the complexity of moving items around (memcpy when trivial, noexcept or not, copy if not movable, etc), and I came up with a traits class that manages everything for you. You give it a destination pointer, and often a source pointer, and the traits class will do the rest.

This is already very useful to have, but then I realized that it could also easily do a destructive move. By specializing the traits class for a destructively movable item (like unique_ptr) it can optimally move the items from the source to the destination memory. All container classes can then simply use item_traits to move items around whenever needed.

Here is a simplification of my current implementation:
template <typename Item>
struct item_traits
{
     using value_type = Item;
     using pointer = value_type*;
     using const_pointer = const value_type*;
     using size_type = std::size_t;

     static void construct(pointer destination, size_type size);
     static void destruct(pointer destination, size_type size);
     static void copy(pointer destination, const_pointer source, size_type size);
     static void move(pointer destination, pointer source, size_type size);
     static void destructive_move(pointer destination, pointer source, size_type size);
};

It would of course have a non specialized version that works for all types and uses type_traits to determine the optimal way to move things around, and destructive_move would simply call move + destruct.

Are there any major issues with this idea that would prevent it from standardization?

Received on 2021-05-03 04:22:10