Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!ulysses!andante!alice!ark From: ark@alice.UUCP (Andrew Koenig) Newsgroups: comp.lang.c++ Subject: Re: operator new() scoping Keywords: storage management garbage collection new delete private Message-ID: <9461@alice.UUCP> Date: 10 Jun 89 14:40:21 GMT References: <1989Jun7.115321.22620@mntgfx.mentor.com> <242@pink.ACA.MCC.COM> Organization: AT&T Bell Laboratories, Liberty Corner NJ Lines: 62 In article <242@pink.ACA.MCC.COM>, rfg@pink.ACA.MCC.COM (Ron Guilmette) writes: > In article <1989Jun7.115321.22620@mntgfx.mentor.com> nmyers@mntgfx.mentor.com (Nathan Myers) writes: > ^ >A self-consistent alternative to the posted semantics is: > ^ >1. Member operator new(size_t, class Foo) doesn't hide global ::new(size_t). > ^^^^^^^^^^^^^ > > Do you mean ::operator new(size_t) ? > > ^ >2. Member operator new(size_t) may be declared private. > ^ >3. "::new T" is not valid syntax. (It seems unnecessary, and dangerous.) > ^^^^^^^^ > > Did you mean ::operator new T ? I guess it's time for me to jump in again. An example: class T { public: void* operator new(size_t); void operator delete(); // other stuff }; void f() { T* tp1 = new T; // calls T::operator new T* tp2 = ::new T; // calls ::operator new T* tp3 = T[10]; // calls ::operator new delete tp1; // calls T::operator delete ::delete tp2; // calls ::operator delete delete[10] tp3; // calls ::operator delete } When you say `new T' it looks for `operator new' using the usual scope rules as if you were in the definition of a member function of T. That is: it first looks for T::operator new, then it searches the base class(es) of T, and finally it looks in the global scope. When you say `::new T' it skips T and all its base classes and goes straight to the global scope. Most people will never use ::new or ::delete; that's why they have a funny kind of syntax. They are there to help authors of container classes. For example, suppose you're writing an array-like class that will contain objects of arbitrary type. Once C++ gets templates, that will be easy, but even now it can be done reasonably effectively through the C preprocessor. Now, suppose you've written a class T and I want to make a container that contains T objects? My container had better control the memory allocation for the objects it contains, so that it can free the objects when the container itself is freed. But how can the container control memory allocation for T if T itself controls its memory allocation? Evidently we need a mechnism for overriding a class' request to control its own memory. That is the purpose of ::new and ::delete. -- --Andrew Koenig ark@europa.att.com