Drake
is_memcpy_movable.h
Go to the documentation of this file.
1 #include <cstdlib>
2 #include <cstring>
3 #include <functional>
4 #include <memory>
5 #include <type_traits>
6 
7 namespace drake {
8 namespace test {
21 template <typename T, typename InvariantPred = std::equal_to<T>>
22 bool IsMemcpyMovable(const T& value,
23  const InvariantPred& invariant_pred = InvariantPred()) {
24  // 1. Create ptr_to_original via placement-new.
25  auto original_storage = std::make_unique<
26  typename std::aligned_storage<sizeof(T), alignof(T)>::type>();
27  T* const ptr_to_original{new (original_storage.get()) T{value}};
28 
29  // 2. Create ptr_to_moved from ptr_to_original via memcpy.
30  auto moved_storage = std::make_unique<
31  typename std::aligned_storage<sizeof(T), alignof(T)>::type>();
32  T* const ptr_to_moved{reinterpret_cast<T* const>(moved_storage.get())};
33  memcpy(ptr_to_moved, ptr_to_original, sizeof(T));
34 
35  // 3. Free original_storage.
36  original_storage.reset();
37 
38  // 4. Check if the invariant between value and ptr_to_moved hold.
39  const bool out{invariant_pred(value, *ptr_to_moved)};
40 
41  ptr_to_moved->T::~T();
42  return out;
43 }
44 } // namespace test
45 } // namespace drake
Definition: automotive_demo.cc:88
bool IsMemcpyMovable(const T &value, const InvariantPred &invariant_pred=InvariantPred())
Checks if value of T type is movable via memcpy.
Definition: is_memcpy_movable.h:22
int value
Definition: copyable_unique_ptr_test.cc:61