Advertisement
tyler569

kinda c++ rust things

Aug 25th, 2018
383
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1.  
  2. #include <cstdio>
  3.  
  4. template <typename T>
  5. struct const_ref;
  6.  
  7. template <typename T>
  8. struct mut_ref;
  9.  
  10. struct unsafe_op {};
  11.  
  12. template <typename T>
  13. struct safe_ptr {
  14.     long refcnt;
  15.     T *data;
  16.  
  17.     safe_ptr() : refcnt(0), data(new T) {}
  18.     safe_ptr(T val) : refcnt(0), data(new T) {
  19.         *data = val;
  20.     }
  21.     ~safe_ptr() { delete data; }
  22.     safe_ptr(safe_ptr const&) = delete;
  23.  
  24.     const_ref<T> operator &() {
  25.         if (refcnt >= 0)
  26.             return const_ref<T>{this};
  27.         else
  28.             throw unsafe_op{};
  29.     }
  30.  
  31.     mut_ref<T> operator +() {
  32.         if (refcnt == 0)
  33.             return mut_ref<T>{this};
  34.         else
  35.             throw unsafe_op{};
  36.     }
  37. };
  38.  
  39. template <typename T>
  40. struct const_ref {
  41.     safe_ptr<T>& ptr;
  42.  
  43.     const_ref(safe_ptr<T> *upstream)
  44.       : ptr(*upstream) {
  45.         ptr.refcnt += 1;
  46.     }
  47.  
  48.     ~const_ref() {
  49.         ptr.refcnt -= 1;
  50.     }
  51.  
  52.     T const& operator *() {
  53.         return *ptr.data;
  54.     }
  55. };
  56.  
  57. template <typename T>
  58. struct mut_ref {
  59.     safe_ptr<T>& ptr;
  60.  
  61.     mut_ref(safe_ptr<T> *upstream)
  62.       : ptr(*upstream) {
  63.         ptr.refcnt -= 1;
  64.     }
  65.  
  66.     ~mut_ref() {
  67.         ptr.refcnt += 1;
  68.     }
  69.  
  70.     T& operator *() {
  71.         return *ptr.data;
  72.     }
  73. };
  74.  
  75. int main() {
  76.     safe_ptr<int> x { 1 };
  77.  
  78.     {
  79.         auto ref = &x;
  80.         // *ref = 100; // would fail for modification of const
  81.         auto ref2 = &x;
  82.         printf("%i", *ref, *ref2);
  83.  
  84.         // auto mut_ref = +x; // would fail for taking mutable ref while const refs exist
  85.     }
  86.  
  87.     {
  88.         auto mut_ref = +x;
  89.         *mut_ref = 10;
  90.     }
  91.  
  92.     {
  93.         auto ref = &x;
  94.         printf("%i", *ref);
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement