operator new
in C++ both allocates and initializes memory (by calling the default constructor). What if I want the memory to be uninitialized? How do I allocate memory in that case?
In C I could have used malloc
for instance which would just allocate memory, not initialize it.
It is possible, but a little tricky to separate allocation from construction. (Bjarne Stroustrup and I discussed this at length, ca. 1985.) What you have to do is to use ::operator new to obtain raw memory. Later on, you can use placement-new or whatever to do the initialization if the object-type requires it. That is how the the default allocator for the STL containers separates allocation and construction.
This obtains raw memory for an object of type U:
Speaking of STL... You can specify your own allocator for the ::std:: containers. For example, if you allocate arrays of floats using std::vector<float>, it will gratuitously initialize them to zeros. (There is a specialization for vector<float>.) You can instead roll your own: std::vector<float, my_own_allocator>.
The custom allocator in the following link inherits functions from the default allocator to do almost everything - including the allocation of raw memory. It overrides the default behavior of construct() - so as to do nothing - when the actual constructor is trivial and cannot throw an exception.
--> Is it possible? std::vector<double> my_vec(sz); which is allocated but not initialized or filled
See how it uses placement new.
Your allocator could even be written such that when compiling for debug, it fills the array with illegal numbers (NaN's), and leaves the memory uninitialized when compiling for release. Some of the nastiest bugs I have ever seen came about when default zeros worked -- until they didn't. DISTRUST DEFAULTS.
One more capital letter thing... AVOID EARLY OPTIMIZATION. Are the computer cycles you save from not initializing objects twice actually worth the effort?