fork download
  1. #include <iostream>
  2. #include <utility>
  3. #include <cstddef>
  4.  
  5. template <typename T>
  6. struct my_shared_ptr
  7. {
  8. my_shared_ptr() : rc(0) {}
  9.  
  10. template <typename... Args>
  11. my_shared_ptr(Args&&... args)
  12. : rc(new refcount_block(std::forward<Args>(args)...))
  13. {}
  14.  
  15. T& operator * ()
  16. {
  17. return *rc->ptr();
  18. }
  19.  
  20. T* operator -> ()
  21. {
  22. return rc->ptr();
  23. }
  24.  
  25. ~my_shared_ptr()
  26. {
  27. if(!--rc->refs)
  28. delete rc;
  29. }
  30.  
  31. private:
  32. struct refcount_block
  33. {
  34. template <typename... Args>
  35. refcount_block(Args&&... args)
  36. : refs(1)
  37. {
  38. new (object) T(std::forward<Args>(args)...);
  39. }
  40.  
  41. ~refcount_block()
  42. {
  43. ptr()->~T();
  44. }
  45.  
  46. T* ptr()
  47. {
  48. return reinterpret_cast<T*>(object);
  49. }
  50.  
  51. std::size_t refs;
  52. char object[sizeof(T)]; // alignas(T)
  53. };
  54.  
  55. refcount_block* rc;
  56. };
  57.  
  58. int main()
  59. {
  60. std::cout << sizeof(int*) << '\n'
  61. << sizeof(my_shared_ptr<int>) << '\n';
  62. }
Success #stdin #stdout 0s 2828KB
stdin
Standard input is empty
stdout
4
4