copy_ptr.t.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. //
  2. // copy_ptr.t.h
  3. // pointers
  4. //
  5. // Created by Sam Jaffe on 1/5/17.
  6. //
  7. #pragma once
  8. #include <cxxtest/TestSuite.h>
  9. #include "copy_ptr.hpp"
  10. class copy_ptr_TestSuite : public CxxTest::TestSuite {
  11. private:
  12. struct copy_me {};
  13. class base {
  14. public:
  15. virtual ~base() {}
  16. virtual base* clone() const = 0;
  17. virtual int id() const = 0;
  18. };
  19. class derived_0 : public base {
  20. public:
  21. static const constexpr int ID = 0;
  22. virtual base * clone() const override { return new derived_0; }
  23. virtual int id() const override { return ID; }
  24. };
  25. class derived_1 : public base {
  26. public:
  27. static const constexpr int ID = 1;
  28. virtual base * clone() const override { return new derived_1; }
  29. virtual int id() const override { return ID; }
  30. };
  31. public:
  32. void test_copy_new_obj() {
  33. copy_ptr<copy_me> c1 { new copy_me };
  34. copy_ptr<copy_me> c2 { c1 };
  35. TS_ASSERT_DIFFERS( c1.get(), c2.get() );
  36. }
  37. void test_copy_object_is_deep_equals() {
  38. using vec_t = std::vector<int>;
  39. vec_t my_vec = { 1, 3, 5, 3, 6, 1, 2, -1, 0 };
  40. copy_ptr<vec_t> c1{ new vec_t{ my_vec } };
  41. TS_ASSERT_EQUALS( *c1, my_vec );
  42. copy_ptr<vec_t> c2{ c1 };
  43. TS_ASSERT_EQUALS( *c2, *c1 );
  44. }
  45. void test_clone_polymorpic_object() {
  46. using ptr_t = clone_ptr<base, &base::clone>;
  47. ptr_t c0 { new derived_0 };
  48. TS_ASSERT_EQUALS( ptr_t( c0 )->id(), derived_0::ID);
  49. ptr_t c1 { new derived_1 };
  50. TS_ASSERT_EQUALS( ptr_t( c1 )->id(), derived_1::ID);
  51. }
  52. void test_does_own() const {
  53. bool has_delete{false};
  54. struct test_t {
  55. ~test_t() { _r = true; }
  56. bool & _r;
  57. };
  58. test_t * test_struct = new test_t{has_delete};
  59. copy_ptr<test_t, nullptr>{ std::move(test_struct) };
  60. TS_ASSERT_EQUALS(has_delete, true);
  61. }
  62. };