c++ - ostream operator shouldn't be calling overloaded new operator? -
i reading thinking in c++ (vol 1 - page-597). came across concept of overloading global new/delete operator.
#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 int"); int* p = new int(47); delete p; puts("creating & destroying s"); s* s = new s; delete s; puts("creating & destroying s[3]"); s* sa = new s[3]; delete []sa; }
taking example says following :-
notice printf( ) , puts( ) used rather iostreams. because when iostream object created (like global cin, cout, , cerr), calls new allocate memory. printf( ), don’t deadlock because doesn’t call new initialize itself.
now check correctness of above statement, included iostream library , added cout statement in conttructor in hope of getting infinite loop expecting cout call new , infinite loop. worked normal. no ambiquity or infinite loop.
am missing here??
Comments
Post a Comment