What is the objective of scoped pointer? to my understanding, the scoped pointer manages the memory within a block of code. If i want to declare a variable within a block , i can just declare it on a stack and not worry about cleaning.
Unlike stack-based data, scoped_ptr has a reset() member -- in other words, you can construct/destruct to your heart's content. With this, you can use a null pointer (technically operator unspecified-bool-type
) as a flag indicating whether or not there is a constructed object at any given time. It also allows you to sequence construction/destruction independently from the variable scope if that is needed.
Also, consider that you can declare a scoped_ptr as a class member, not just as a stack variable. The docs suggest using scoped_ptr to implement the handle/body idiom (to hide the class' implementation details).
Finally, to elaborate on DeadMG's point "Not if it's of dynamic type", you can use scoped_ptr to implement a polymorphic operation:
{
scoped_ptr<Base> a( mode ? new DerivedA : new DerivedB );
a->polymorphic_function();
}
It's not really possible to do this with simple stack-based allocation.
Also see here: C++0x unique_ptr replaces scoped_ptr taking ownership?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With