[lug] new operator in C++

D. Stimits stimits at idcomm.com
Sat Apr 27 14:56:04 MDT 2002

Stephen Queen wrote:
> "D. Stimits" wrote:
> >
> > Older compilers behaved similar to malloc, and returned NULL if failed.
> > Newer ones (g++) will throw an exception. To override this and get older
> > NULL behavior, you can create your own custom allocator, or else do the
> > easy thing, use the nothrow argument. E.G.:
> >   myClass* oTheClass = NULL;
> >   oTheClass = new(nothrow) myClass;
> >   assert(oTheClass);
> >
> > D. Stimits, stimits at idcomm.com
> >
> > PS: If in doubt, just use (nothrow) and see if the compiler
> > complains...if it doesn't, then you have a compiler that supports
> > exception throwing for failures of new.
> > _______________________________________________
> Let me rephrase my question. In the following example,
> int* intptr=new int;
If this fails, it could either throw an exception or it could set intptr
to NULL. You don't know unless you know the compiler (and possibly also
the libstdc++).

> cout<<*intptr<<endl;
> Is the newly created memory's value guaranteed to be zero. Will the out put
> of the example be guaranteed to be zero.

If you use the (nothrow) option, and allocation fails, yes. Otherwise,
the code above would throw an uncaught exception and exit abnormally. If
you want to be guaranteed of NULL, use nothrow, and typecast your
pointer to size_t (assuming a flavor of UNIX). Now if allocation fails,
you can be guaranteed that the program will not continue using garbage
values, but it may never reach a test against NULL if it throws
exceptions. Try instead:
  int* intptr=new(nothrow) int;
  cout<< (size_t)(intptr) << endl;

NOTE: The original "cout<<*intptr<<endl" would output the value pointed
to by intptr, and if memory allocation had failed, this would be a
segmentation fault/memory violation since the pointer at NULL cannot be
dereferenced...you are interested in printing the pointer itself, not
what it points at, if you are testing addresses and viewing addresses.
One would assert via assert(intptr), rather than assert(*intptr).

> More importantly, where is a good source of information on this? Do I need
> to just start digging through the include header files to figure this stuff
> out? I can do that, but it is sooo time consuming, and if some one has
> already documented it, where can I find it?

I've always just had to dig around. Looking at the header files for the
operators can help, you'll see the throw specification at times.
Stroustrup is a good reference on the topic, but does not include
specifics for individual compilers or platforms.

D. Stimits, stimits at idcomm.com

More information about the LUG mailing list