C++ Suppress Automatic Initialization and Destruction
- by Travis G
How does one suppress the automatic initialization and destruction of a type? While it is wonderful that T buffer[100] automatically initializes all the elements of buffer, and destroys them when they fall out of scope, this is not the behavior I want.
#include <iostream>
static int created = 0,
destroyed = 0;
struct S
{
S()
{
++created;
}
~S()
{
++destroyed;
}
};
template <typename T, size_t KCount>
class Array
{
private:
T m_buffer[KCount];
public:
Array()
{
// some way to suppress the automatic initialization of m_buffer
}
~Array()
{
// some way to suppress the automatic destruction of m_buffer
}
};
int main()
{
{
Array<S, 100> arr;
}
std::cout << "Created:\t" << created << std::endl;
std::cout << "Destroyed:\t" << destroyed << std::endl;
return 0;
}
The output of this program is:
Created: 100
Destroyed: 100
I would like it to be:
Created: 0
Destroyed: 0
My only idea is to make m_buffer some trivially constructed and destructed type like char and then rely on operator[] to wrap the pointer math for me, although this seems like a horribly hacked solution. Another solution would be to use malloc and free, but that gives a level of indirection that I do not want.