#include <vector>
#include <new>
template <class t>//templated class
class Square
{
public:
t side;
//inline constructor
Square(t side){ this->side = side; }
~Square() { }
t getSide();
};
int main()
{
const unsigned num_elements = 4;
{
// manually:
void* raw_memory = operator new(sizeof(Square<double>) * num_elements);
Square<double>* sqr = static_cast<Square<double>*>(raw_memory);
// construct each of the 4 squares:
for (unsigned i = 0; i < num_elements; ++i)
new (sqr + i) Square<double>(i*3.14);
// use the Squares here
// then, what was constructed must be destructed:
for (unsigned i = 0; i < num_elements; ++i)
(sqr + i)->~Square<double>();
// and the memory deallocated.
operator delete(sqr);
}
//using std::vector:
{
std::vector<Square<double>> sqr;
for (unsigned i = 0; i < num_elements; ++i)
sqr.emplace_back(i*3.14);
// use the squares here...
// then the objects are automatically destructed and
// memory freed when sqr goes out of scope.
}
}