On 27 Feb, 09:44, rpbg...@yahoo.com (Roland Pibinger) wrote:
On Mon, 26 Feb 2007 23:46:45 GMT, Mark P wrote:
Roland Pibinger wrote:
A* p = new A; // ok
A a; // not ok
Depends how literally you want to interpret the OP's question. In any
event, AFAIK there's no way to satisfy your interpretation. True?
Probably not for a compile time solution but you could e.g. overload
operator new for the class and do some hacks there to avoid creation
on the stack at runtime. But I don't know a good reason why one would
want to do that.
One reason is that the semantics of heap allocated objects are
different in an important way. You are in control of the lifetime of
the object. Hence smart pointers such as shared_ptr.( Though you can
violate the guarantee with shared_ptr using a 'null deleter'.) With
stack allocated objects you are not. In fact new could be looked at as
a modifier to the type of an object, like const.
Also note that the straight new operator does two things with
orthogonal purpose. One it allocates memory, Two it constructs an
object.
The purpose behind the allocation can be either that you want the
object to be more or less permanent, outside control of the stack, or
because you need an object whose size cannot be known until runtime or
both.
One downside of acquiring a chunk of memory at runtime is that it can
be a slow business. The other is that the compiler finds less
opportunity for optimisation.
All these things add up to important differences between 'auto' and
heap allocated objects.
regards
Andy Little