c++ - Constructor call when operator new failed -
i’m trying implement technique test failing operator new
described in http://www.codeproject.com/articles/6108/simulating-memory-allocation-failure-for-unit-test.
this sample code beingness tested:
varray* arr = new varray(1u, 3u, true);
i can create new
homecoming null
instead of allocating memory. in case, programme should go on next line (which should test if arr == null
) , in msvc.
however, constructor of varray
still called after failed new
in gcc. , since this
null
, results in sigsegv on first assignment property. seems wrong behavior according c++03 standard: http://stackoverflow.com/a/11514528/711006
my implementation of operators new
, delete
follows.
unsigned int operatorplainnewfailsafter = uint_max; void* operator new(const size_t _size) throw() { void* result; if(operatorplainnewfailsafter == 0u) { result = null; } else { result = malloc(_size); operatorplainnewfailsafter--; } homecoming result; } void operator delete(void* _memory) throw() { free(_memory); }
what miss?
the c++ standard requires allocation function (e.g. basic operator new
) fails throwing std::bad_alloc
exception, if fails. it's not allowed homecoming nullpointer. when homecoming nullpointer have undefined behavior, , yes, 1 possible consequence constructor called.
c++ gcc c++03
No comments:
Post a Comment