Topic: Calling new w/o a type specifier


Author: sdm@cs.brown.edu (Scott Meyers)
Date: Thu, 12 Mar 1992 03:37:01 GMT
Raw View
Can operator new be called without a type specifier?  If so, what does it
return?  What does it do?

Consider this example:

    class Airplane {};

    main()
    {
      void *p = ::operator new(256*sizeof(Airplane));
    }

The grammar summary in the ARM seems to imply that this is not legal --
section 17.2 (p. 390) shows no production for an allocation-expression that
contains no type specfier.  Yet both cfront 3.0.1 and g+ 2.0 accept this
program without complaint.

If main() is changed to contain this single statement,

      Airplane *p = ::operator new(256*sizeof(Airplane));

g++ still takes it, but cfront complains about initializing an Airplane*
pointer with a void* pointer.

So what gives?  Can new be called without specifying a type?  If so, what
is the return type of calling new in that manner?  Finally, if the
expression "::operator new(1000)" is legal, what are its semantics?

Scott



-------------------------------------------------------------------------------
What do you say to a convicted felon in Providence?  "Hello, Mr. Mayor."




Author: bs@alice.att.com (Bjarne Stroustrup)
Date: 13 Mar 92 14:51:58 GMT
Raw View

sdm@cs.brown.edu (Scott Meyers @ Brown University Department of Computer Science) asks

 > Can operator new be called without a type specifier?  If so, what does it
 > return?  What does it do?
 >
 > Consider this example:
 >
 >     class Airplane {};
 >
 >     main()
 >     {
 >       void *p = ::operator new(256*sizeof(Airplane));
 >     }
 >
 > The grammar summary in the ARM seems to imply that this is not legal --
 > section 17.2 (p. 390) shows no production for an allocation-expression that
 > contains no type specfier.  Yet both cfront 3.0.1 and g+ 2.0 accept this
 > program without complaint.

The point that escaped you is that `operator new()' is a function. It is declared:

 void* operator new(t_size);

in <new.c>. Strictly speaking your code should compile only if you included <new.h>
but cfront (and as it seems gcc) happens to know about this function anyway because
it uses it to implement the free store operator `new.'

(You were looking in the wrong chapter of the ARM. Have a look at section 12.5).

 > If main() is changed to contain this single statement,
 >
 >       Airplane *p = ::operator new(256*sizeof(Airplane));
 >
 > g++ still takes it, but cfront complains about initializing an Airplane*
 > pointer with a void* pointer.

Presumably gcc simply accepts the unsafe void* to Airplane* conversion ( like ANSI C).

 > So what gives?  Can new be called without specifying a type?

The new OPERATOR can't. The `operator new()' FUNCTION can.

 > If so, what
 > is the return type of calling new in that manner?  Finally, if the
 > expression "::operator new(1000)" is legal, what are its semantics?

ARM 12.5.