I’m reading “Thinking in C++” and I’m confused by the new operator. Here is the code from the book:
//: C13:ArrayOperatorNew.cpp
// Operator new for arrays
#include <new> // Size_t definition
#include <fstream>
using namespace std;
ofstream trace("ArrayOperatorNew.out");
class Widget
{
enum { sz = 10 };
int i[sz];
public:
Widget() { trace << "*"; }
~Widget() { trace << "~"; }
void* operator new(size_t sz)
{
trace << "Widget::new: "
<< sz << " bytes" << endl;
return ::new char[sz];
}
void operator delete(void* p)
{
trace << "Widget::delete" << endl;
::delete []p;
}
void* operator new[](size_t sz)
{
trace << "Widget::new[]: "
<< sz << " bytes" << endl;
return ::new char[sz];
}
void operator delete[](void* p)
{
trace << "Widget::delete[]" << endl;
::delete []p;
}
};
int main()
{
trace << "new Widget" << endl;
Widget* w = new Widget;
trace << "\ndelete Widget" << endl;
delete w;
trace << "\nnew Widget[25]" << endl;
Widget* wa = new Widget[25];
trace << "\ndelete []Widget" << endl;
delete []wa;
} ///:~
and here is the content of the trace in “ArrayOperatorNew.out”
new Widget
Widget::new: 40 bytes
*
delete Widget
~Widget::delete
new Widget[25]
Widget::new[]: 1004 bytes
*************************
delete []Widget
~~~~~~~~~~~~~~~~~~~~~~~~~
Widget::delete[]
I’m confused about the number 1004. Why it’s not 1000? The book says:
This extra four bytes is where the
system keeps information about the
array, in particular, the number of
objects in the array.
But what’s the system? How is this accomplished? Compiler helps here?
When using new[] the runtime needs some way to remember the size of the array allocated, so it knows how much to deallocate when using delete[]. In your particular implementation it’s way of remembering is allocating the extra four bytes which hold the size (it doesn’t have to work this way).
You can read more about this in the C++ FAQ.