[Assorted-commits] SF.net SVN: assorted:[1058] sandbox/trunk/src/cc/overload_new.cc
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-11-06 05:10:02
|
Revision: 1058 http://assorted.svn.sourceforge.net/assorted/?rev=1058&view=rev Author: yangzhang Date: 2008-11-06 05:09:46 +0000 (Thu, 06 Nov 2008) Log Message: ----------- added demo of overloading new Added Paths: ----------- sandbox/trunk/src/cc/overload_new.cc Added: sandbox/trunk/src/cc/overload_new.cc =================================================================== --- sandbox/trunk/src/cc/overload_new.cc (rev 0) +++ sandbox/trunk/src/cc/overload_new.cc 2008-11-06 05:09:46 UTC (rev 1058) @@ -0,0 +1,76 @@ +// Great thread: http://bytes.com/forum/thread521533.html +// +// - "operator new" != "new operator" +// - "new operator" consists of (1) allocation and (2) construction +// - "operator new" is the (1) allocation in "new operator" +// +// See also: man g++, search for -fcheck-new + +// #include <cstddef> // size_t +#include <new> // bad_alloc, size_t +#include <cstdlib> // malloc +#include <iostream> // cout, endl + +// You can globally *replace* operator new. There are two ways to replace +// operator new. + +#if 1 + +// Option 1: You can throw an exception when something goes awry. + +void * +operator new(std::size_t sz) throw(std::bad_alloc) +{ + std::cout << "calling operator new that throws exceptions" << std::endl; + // If you uncomment this line, the compiler will complain. + // return NULL; + void *p = malloc(sz); + if (!p) throw std::bad_alloc(); + return p; +} + +#else + +// Option 2: You can return NULL when something goes awry. + +void * +operator new(std::size_t sz) throw() +{ + std::cout << "calling operator new that returns NULL" << std::endl; + return malloc(sz); +} + +#endif + +// You can also *overload* operator new for a specific class. As with global +// replacement, you can either go with a NULL-returning new or an +// exception-throwing new. + +class C +{ + public: + int x; + + void * + operator new(std::size_t sz) throw(std::bad_alloc) + { + std::cout << "calling C::operator new" << std::endl; + // Must use ::, otherwise will recurse into self infinitely. + return ::operator new(sz); + } +}; + +int +main() +{ + // You can actually call operator new directly anywhere. + void *p = operator new(1024); + C *c = new C; + return 0; +} + +// Output: +// +// calling operator new that throws exceptions +// calling C::operator new +// calling operator new that throws exceptions This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |