Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why scoped pointers in boost

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.

like image 656
Jimm Avatar asked May 24 '12 00:05

Jimm


1 Answers

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?

like image 93
Brent Bradburn Avatar answered Oct 07 '22 07:10

Brent Bradburn