fork(1) download
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <utility>
  4.  
  5. template <typename T>
  6. struct noop_destructor {
  7. public:
  8. typedef T* pointer;
  9. typedef const T* const_pointer;
  10. typedef T& reference;
  11. typedef const T& const_reference;
  12.  
  13. template<typename... Args>
  14. noop_destructor(Args&&... args) {
  15. new (reinterpret_cast<void*>(wrapped_data)) T(std::forward<Args>(args)...);
  16. }
  17.  
  18. explicit noop_destructor(const noop_destructor& rhs) {
  19. std::copy(rhs.wrapped_data,rhs.wrapped_data+sizeof(T),wrapped_data);
  20. }
  21.  
  22. noop_destructor& operator=(const noop_destructor& rhs) {
  23. std::copy(rhs.wrapped_data,rhs.wrapped_data+sizeof(T),wrapped_data);
  24. return *this;
  25. }
  26.  
  27. pointer operator->() {
  28. return reinterpret_cast<pointer>(wrapped_data);
  29. }
  30. const_pointer operator->() const {
  31. return reinterpret_cast<const_pointer>(wrapped_data);
  32. }
  33. reference operator*() {
  34. return *reinterpret_cast<pointer>(wrapped_data);
  35. }
  36. const_reference operator*() const {
  37. return *reinterpret_cast<const_pointer>(wrapped_data);
  38. }
  39. private:
  40. uint8_t wrapped_data[sizeof(T)] __attribute__ ((aligned (__BIGGEST_ALIGNMENT__)));
  41. };
  42.  
  43.  
  44. class A {
  45. public:
  46. A() : x_() {}
  47. A(int x) : x_(x) {}
  48. ~A() {
  49. std::cout << "noop destructor call of class A" << std::endl;
  50. }
  51. void foo() {
  52. std::cout << "x_ = " << x_ << std::endl;
  53. }
  54.  
  55. private:
  56. int x_;
  57. };
  58.  
  59. int main() {
  60. A a1(5);
  61. noop_destructor<A> a2;
  62.  
  63. a1.foo();
  64. (*a2).foo();
  65. return 0;
  66. }
  67.  
Success #stdin #stdout 0s 3140KB
stdin
Standard input is empty
stdout
x_ = 5
x_ = 0
noop destructor call of class A