fork download
  1. #include <iostream>
  2. #include <cassert>
  3.  
  4. #include <utility> //For std::forward.
  5.  
  6. namespace Memory
  7. {
  8. template<typename Type, typename ...Args>
  9. Type *Allocate(Args&& ...args)
  10. {
  11. //Allocate memory using 'malloc'.
  12. Type *ptr = static_cast<Type*>(malloc(sizeof(Type)));
  13. assert(ptr && "We're probably out of memory.");
  14.  
  15. //Manually call constructor, forwarding the arguments to the constructor.
  16. new (ptr) Type(std::forward<Args>(args)...);
  17.  
  18. //Return the pointer.
  19. return ptr;
  20. }
  21.  
  22. template<typename Type>
  23. void Deallocate(Type* &ptr) //Reference to a pointer. Huh, never had to use that before.
  24. {
  25. //Comment this assert out if you like the ability to pass null to 'delete'.
  26. assert(ptr && "Trying to allocate an already NULL pointer.");
  27.  
  28. //Call the destructor manually.
  29. ptr->~Type();
  30.  
  31. //Deallocate the memory.
  32. free(ptr);
  33.  
  34. //Nullify the pointer (we got a reference to a pointer, so this is nulling the pointer that was passed into the function).
  35. //Comment this line out if you want to do the nulling yourself.
  36. ptr = nullptr;
  37. }
  38.  
  39. } //End of namespace.
  40.  
  41. class MyClass
  42. {
  43. public:
  44. MyClass(const std::string &str, int value)
  45. {
  46. std::cout << "MyClass(" << str << "," << value << ")" << std::endl;
  47. }
  48.  
  49. ~MyClass()
  50. {
  51. std::cout << "~MyClass()" << std::endl;
  52. }
  53. };
  54.  
  55. int main()
  56. {
  57. std::cout << "---------- Start ----------" << std::endl;
  58.  
  59. MyClass *myClass = Memory::Allocate<MyClass>("Hello", 357);
  60.  
  61. std::cout << "Pointer address: " << myClass << std::endl;
  62. std::cout << "...program does stuff..." << std::endl;
  63.  
  64. Memory::Deallocate(myClass);
  65.  
  66. std::cout << "---------- End ----------" << std::endl;
  67. std::cout << "Pointer address: " << myClass << std::endl;
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
---------- Start ----------
MyClass(Hello,357)
Pointer address: 0x2b2a9bbf2c30
...program does stuff...
~MyClass()
---------- End ----------
Pointer address: 0