How does one suppress the automatic initialization and destruction of a type? While it is wonderful that T buffer[100] automatically initializes all the elemen
If you want to be like vector, you should do something like this:
template
class my_vector
{
T* ptr; // this is your "array"
// ...
public:
void reserve(size_t n)
{
// allocate memory without initializing, you could as well use malloc() here
ptr = ::operator new (n*sizeof(T));
}
~my_vector()
{
::operator delete(ptr); // and this is how you free your memory
}
void set_element(size_t at, const T& element = T())
{
// initializes single element
new (&ptr[at]) T(element); // placement new, copies the passed element at the specified position in the array
}
void destroy_element(size_t at)
{
ptr[at].~T(); // explicitly call destructor
}
};
This code is obviously for demonstration only, I have omitted my_vector's copy-constructor and any tracking on what's created and what not (calling destructor on a location you haven't called constructor for is probably undefined behavior). Also, STL's vector allocations and deallocations are abstracted away through the use of allocators (the second template argument of vector).
Hope that helps