While reading Bruce Eckel i came across the following example:
#include <cstdio>
#include <cstdlib>
using namespace std;
void* operator new(size_t sz)
{
printf("operator new: %d Bytes\n", sz);
void* m = malloc(sz);
if(!m) puts("out of memory");
return m;
}
void operator delete(void* m)
{
puts("operator delete");
free(m);
}
class S {
int i[100];
public:
S() { puts("S::S()"); }
~S() { puts("S::~S()"); }
};
int main() {
puts("creating & destroying an int");
int* p = new int(47);
delete p;
puts("creating & destroying an s");
S* s = new S;
delete s;
puts("creating & destroying S[3]");
S* sa = new S[3];
delete []sa;
}
I am having doubt with following statement:
-
Notice that
printf( )andputs( )are used rather than iostreams. This is because when aniostreamobject is created (like the globalcin,cout, andcerr), it callsoperator newto allocate memory. Withprintf( ), you don’t get into a deadlock because it doesn’t callnewto initialize itself.
However, when i am running the program after replacing put withcouti am getting no such deadlock. Can anyone explain that? -
operator newreturns a void pointer, but finally we are getting pointer to a dynamically allocated object. So is it a constructor that returns a pointer to the object (this, though the constructor doesn’t have a return type) or its the compiler that does i internally?
Use of
printf()to avoid a recursive call intooperator new()is a safety measure – just to be sure it works. How do you know use ofiostreamnever ever causes a call tooperator new()function?You’re confusing new expression (a language construct) with
operator new()function. new expression indeed returns a typed pointer, but the a call tooperator new()function is done “under the hood” andoperator new()function returnsvoid*. The compiler generates all necessary code for that.