Re: boost::scoped_ptr rationale?
Marcel M?ller <news.5.maazl@spamgourmet.com> wrote:
Did you ever succeed to instantiate a polymorphic object on the stack?
Probably not. The exact type must be known at compile time for this
purpose. So, no factory pattern.
If you don't know the actual type of the object at compile time in
the current scope, but nevertheless want to use scoped_ptr to handle
it, it would mean that there has to be some function which you call from
the current scope and which returns a raw pointer to the object it
allocated (leaving the responsibility of deleting the object up to the
calling code). While this is certainly something you can do, I would say
it's a pretty bad design (allocating something and then leaving the
deletion up to the calling code is asking for trouble in a non-garbage-
collected environment).
If I understood correctly, that "factory" function can certainly not
return a scoped_ptr (because it's non-copyable).
Of course it could take a scoped_ptr reference as parameter and put
the allocated object there. Feels a bit contrived, though.
The lifetime of stack objects is restricted to {} blocks.
So is the lifetime of an object handled by scoped_ptr (the object cannot
be shared nor transferred to anything else). So?
scoped_ptr is one of the easiest ways to provide exception safety for
local dynamic objects.
I didn't doubt that. My question is why you would allocate the object
dynamically in the first place.