fork download
  1. #include <iostream>
  2.  
  3. template<typename T>
  4. class RAIIpointer
  5. {
  6. private:
  7. T* _raw_pointer;
  8. public:
  9. explicit RAIIpointer(T* managed): _raw_pointer(managed)
  10. {
  11. std::cout << "\t\tAllocating memory for single object\n";
  12. }
  13. ~RAIIpointer()
  14. {
  15. std::cout << "\t\tReleasing memory for single object\n";
  16. delete _raw_pointer;
  17. }
  18. };
  19.  
  20. template<typename T>
  21. class RAIIpointer<T[]> // array specialization
  22. {
  23. private:
  24. T* _raw_pointer;
  25. public:
  26. explicit RAIIpointer(T* managed): _raw_pointer(managed)
  27. {
  28. std::cout << "\t\tAllocating memory for array\n";
  29. }
  30. ~RAIIpointer()
  31. {
  32. std::cout << "\t\tReleasing memory for array\n";
  33. delete[] _raw_pointer;
  34. }
  35. };
  36.  
  37. int main()
  38. {
  39. std::cout << "Before entering RAII scope\n";
  40. {
  41. std::cout << "\tCreating a smart pointer...\n";
  42. RAIIpointer<int> smart_ptr(new int); // that's it, automatic release when scope ends
  43. RAIIpointer<int[]> smart_ptr_arr(new int[42]); // same
  44. std::cout << "\tDone with it\n";
  45. }
  46. std::cout << "After exiting RAII scope\n";
  47. }
Success #stdin #stdout 0s 3272KB
stdin
Standard input is empty
stdout
Before entering RAII scope
	Creating a smart pointer...
		Allocating memory for single object
		Allocating memory for array
	Done with it
		Releasing memory for array
		Releasing memory for single object
After exiting RAII scope