mjunkin@uvicctr.UVic.CA.UUCP (Michael Junkin) (07/10/90)
Hello: I'm having a bit of trouble with operator new. Specifically, I have a class X for which I often (but not always) want to allocate storage myself but sometimes want to use the builtin operator new. Thus, the class X contains the definition static void *operator new(size_t); The intent is that X *x = new X(...); (1) can be used to allocate and construct local objects while X *x = ::new X(...); (2) is used to allocate and construct global objects of class X. However, this does not work. The C code generated by both the AT&T and SUN version 2.0 compilers is the same in both case 1 and case 2. As an example the program // ********************************* #include <stddef.h> #include <iostream.h> class X { int i; public: X(int n) { i = n; } static void *operator new(size_t); static void operator delete(void *) {} }; void *X::operator new(size_t n) { cout << "allocating locally\n"; return new char[n]; } main() { X *x1 = ::new X(1); X *x2 = new X(2); } // ********************************* when compiled and run produces the output allocating locally allocating locally Have I missed something, or is this a C++ compiler bug? I would appreciate any information on this matter. Thanks in advance, Michael. -- ------------------------------------------------------------------------ *standard disclaimers apply* Michael D. Junkin Department of Computer Science University of Victoria Victoria, B.C. CANADA mjunkin@csr.UVic.ca (internet)
jimad@microsoft.UUCP (Jim ADCOCK) (07/14/90)
In article <1155@uvicctr.UVic.CA.UUCP> mjunkin@uvicctr.UUCP (Michael Junkin) writes: ... >The intent is that > X *x = new X(...); (1) >can be used to allocate and construct local objects while > X *x = ::new X(...); (2) >is used to allocate and construct global objects of class X. ... > static void *operator new(size_t); Interesting. I tried your example on the compiler I've been playing with, and it wouldn't accept the static keyword on operator new, even though E&S implies such use is permissible, but unnecessary. Leaving off "static," my compiler then acts as you would like. Sounds to me like one bug each in two compilers.