Advertisement
Guest User

Untitled

a guest
Oct 4th, 2020
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <exception>
  3. #include <memory>
  4.  
  5.  
  6. // External world
  7.  
  8. typedef void *EXTERNAL_ONE;
  9.  
  10. static EXTERNAL_ONE CreateExternalOne(long i) {
  11.     std::cout << "Creating heavy object" << std::endl;
  12.     return reinterpret_cast<EXTERNAL_ONE>(i);
  13. }
  14.  
  15. static void ReleaseExternalOne(EXTERNAL_ONE resource) noexcept(false) {
  16.     if (resource == nullptr) {
  17.         throw std::exception();
  18.     }
  19.     std::cout << "Releasing heavy object" << std::endl;
  20. }
  21.  
  22.  
  23. static void DoSomethingUseful(EXTERNAL_ONE resource) {
  24.     std::cout << "I am using " << reinterpret_cast<long>(resource) << std::endl;
  25. }
  26.  
  27.  
  28. // Defecate approach
  29. typedef std::unique_ptr<void, decltype(&ReleaseExternalOne)> SmartResource;
  30.  
  31. static SmartResource Create(int i) {
  32.     return SmartResource(CreateExternalOne(i + 22), &ReleaseExternalOne);
  33. }
  34.  
  35. static void defecateApproach() {
  36.     auto resource = Create(14);
  37.     DoSomethingUseful(resource.get());
  38. }
  39.  
  40. //Custom mover inspired by Gost
  41.  
  42. class CustomWrapper {
  43. public:
  44.     EXTERNAL_ONE m_externalOne;
  45.  
  46.     explicit CustomWrapper(EXTERNAL_ONE externalOne) : m_externalOne(externalOne) {
  47.     }
  48.  
  49.     CustomWrapper(const CustomWrapper &other) = delete;
  50.  
  51.     CustomWrapper(CustomWrapper &&other) noexcept: m_externalOne(other.m_externalOne) {
  52.         other.m_externalOne = nullptr;
  53.         std::cout << "Moving, yey" << std::endl;
  54.     }
  55.  
  56.     ~CustomWrapper() {
  57.         if (m_externalOne) {
  58.             ReleaseExternalOne(m_externalOne);
  59.         } else {
  60.             std::cout << "No need to delete dead one" << std::endl;
  61.         }
  62.     }
  63. };
  64.  
  65. static void customApproachAcceptsMover(CustomWrapper wrapper) {
  66.     DoSomethingUseful(wrapper.m_externalOne);
  67. }
  68.  
  69. static void customApproach() {
  70.     customApproachAcceptsMover(CustomWrapper(CreateExternalOne(99)));
  71. }
  72.  
  73. int main() {
  74.     defecateApproach();
  75.     customApproach();
  76.     return 0;
  77. }
  78.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement