fork download
  1. #include <vector>
  2. #include <new>
  3.  
  4. template <class t>//templated class
  5. class Square
  6. {
  7. public:
  8. t side;
  9. //inline constructor
  10. Square(t side){ this->side = side; }
  11.  
  12. ~Square() { }
  13.  
  14. t getSide();
  15. };
  16.  
  17.  
  18. int main()
  19. {
  20. const unsigned num_elements = 4;
  21.  
  22. {
  23. // manually:
  24. void* raw_memory = operator new(sizeof(Square<double>) * num_elements);
  25. Square<double>* sqr = static_cast<Square<double>*>(raw_memory);
  26.  
  27. // construct each of the 4 squares:
  28. for (unsigned i = 0; i < num_elements; ++i)
  29. new (sqr + i) Square<double>(i*3.14);
  30.  
  31. // use the Squares here
  32.  
  33. // then, what was constructed must be destructed:
  34. for (unsigned i = 0; i < num_elements; ++i)
  35. (sqr + i)->~Square<double>();
  36.  
  37. // and the memory deallocated.
  38. operator delete(sqr);
  39. }
  40.  
  41. //using std::vector:
  42. {
  43. std::vector<Square<double>> sqr;
  44. for (unsigned i = 0; i < num_elements; ++i)
  45. sqr.emplace_back(i*3.14);
  46.  
  47. // use the squares here...
  48.  
  49. // then the objects are automatically destructed and
  50. // memory freed when sqr goes out of scope.
  51. }
  52. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Standard output is empty