c++ - overloaded new operator returning NULL memory for new object everytime -


i trying return null overloaded new operator function every time. here program

class xxx{       int n;       public:              void* operator new(size_t){                    cout<<"in operator new"<<endl;                    throw std::bad_alloc();                    //return (void *)null;         //line commented                    } }; int main(int argc,char *argv[]) {    xxx *x1=new xxx;    if(x1)       cout<<sizeof(x1);    else       cout<<"unable allocate memory"<<endl;    return 0; } 

here if use line return (void *)null; pointer x1 gets created not intended program.

and if use line throw std::bad_alloc();, program gets terminated/crashed instantly.

now want know if there way if can bypass "new operator" not allocate memory object.

this code works fine (tested msvc vs2010) , returns nullptr x allocation, requested in question:

#include <iostream> using namespace std;  class x { public:     x() { cout << "x::x()" << endl; }      static void* operator new(size_t size) {         return nullptr;     } };  int main() {     x* px = new x();     if (!px) {         cout << "allocation returned nullptr." << endl;     } else {         cout << "allocation succeeded." << endl;         delete px;         px = nullptr;     } } 

note in modern c++11, may want use nullptr instead of c++98/03 null.

note (void*) cast used in code useless.

moreover, if use throw std:bad_alloc(); inside custom implementation of new, program "crashes" beacuse throw exception never caught.
if insert try...catch(const std::exception&) block in main(), can make program exit in more "controlled" way (including printing error message).


Comments

Popular posts from this blog

Change the color of an oval at click in Java AWT -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -