[Assorted-commits] SF.net SVN: assorted:[1060] sandbox/trunk/src/cc/overload_new.cc
Brought to you by:
yangzhang
From: <yan...@us...> - 2008-11-06 08:43:15
|
Revision: 1060 http://assorted.svn.sourceforge.net/assorted/?rev=1060&view=rev Author: yangzhang Date: 2008-11-06 08:43:12 +0000 (Thu, 06 Nov 2008) Log Message: ----------- added overloading of operator new Modified Paths: -------------- sandbox/trunk/src/cc/overload_new.cc Modified: sandbox/trunk/src/cc/overload_new.cc =================================================================== --- sandbox/trunk/src/cc/overload_new.cc 2008-11-06 08:42:43 UTC (rev 1059) +++ sandbox/trunk/src/cc/overload_new.cc 2008-11-06 08:43:12 UTC (rev 1060) @@ -60,17 +60,57 @@ } }; +// You can add extra parameters to operator new. + +void * +operator new(std::size_t sz, const char file[16], int line) +throw(std::bad_alloc) +{ + std::cout << "calling operator new at " << file << ':' << line << std::endl; + return operator new(sz); +} + +class D +{ + public: + int x; +}; + int main() { // You can actually call operator new directly anywhere. void *p = operator new(1024); - C *c = new C; + std::cout << std::endl; + + // Use C's operator new. + C *a = new C; + std::cout << std::endl; + + // This won't work since we didn't extend C's operator new. + // C *b = new(__FILE__, __LINE__) C; + + // Use the extended operator new. + D *b = new(__FILE__, __LINE__) D; + std::cout << std::endl; + + // Permanently change what 'new' means. +#define new new(__FILE__, __LINE__) + D *c = new D; + std::cout << std::endl; + return 0; } // Output: // // calling operator new that throws exceptions +// // calling C::operator new // calling operator new that throws exceptions +// +// calling operator new at overload_new.cc:94 +// calling operator new that throws exceptions +// +// calling operator new at overload_new.cc:99 +// calling operator new that throws exceptions This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |