Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!usc!ucsd!pacbell.com!ames!vsi1!octopus!sjsumcs!horstman From: horstman@sjsumcs.sjsu.edu (Cay Horstmann) Newsgroups: comp.lang.c++ Subject: Distinguishing stack and heap objects Message-ID: <1990Dec29.013620.23761@sjsumcs.sjsu.edu> Date: 29 Dec 90 01:36:20 GMT Reply-To: horstman@sjsumcs.SJSU.EDU (Cay Horstmann) Organization: San Jose State University Lines: 23 Recently someone asked whether one can distinguish objects allocated with new from those allocated on the stack, and it just occurred to me that this is possible. Ignore this if the technique is an old hat, it is new to me. Give class X a member int fromHeap and a static member int heapFlag. Define all constructors X::X( ... ) to contain the lines fromHeap = heapFlag; heapFlag = 0; and define X::operator new( size_t s ) as { heapFlag = 1; return new char[s]; } If x is any pointer of type X*, then x->fromHeap is true iff x is allocated on the heap. I am using the fact that X::operator new is (acts like?) a static member function and hence can access static members of X. Is this legal? Is it in the spirit of the language? Is it useful? CAN I PATENT IT? Happy new year, Cay