"Roland Pibinger" <rpbg123@yahoo.com> wrote in message
news:43d204e8.439738@news.utanet.at...[color=blue]
> On 20 Jan 2006 13:45:10 -0800,
yinglcs@gmail.com wrote:[color=green]
>>
>>I am reading the Boost scoped_ptr library, and I wonder what is the
>>advantage of using that.[/color]
>
> First let me clarify that I neither endorse 'smart' pointers nor
> 'Boost'.
>[color=green]
>>Here is an example from Boost.org web site:[/color]
> [...][color=green]
>>int main()
>>{
>> boost::scoped_ptr<Shoe> x(new Shoe);[/color]
> [...][color=green]
>>}
>>
>>can't I simple change code to allocate the 'Shoe' object from the stack
>>instead of getting it from the heap, like this:
>>int main()
>>{
>> Shoe shoe;[/color]
> [...][color=green]
>>}
>>
>>since we don't pass scoped_ptr outside the function (that is the
>>functionality of Boost shared_ptr), I don't the advantage of using
>>Boost scoped_ptr.[/color]
>
> Yes you can (and should) do it in that case. The main difference is
> that a scoped_ptr can be 'empty' (point to 0) and can be re-set
> without copying the pointed-to object (although .reset() works
> differently compared to shared_ptr). scoped_ptr isn't safer than a
> real pointer (when you dereference an 'empty' scoped_ptr your program
> probably crashes).[/color]
The key advantage of scoped_ptr over a real pointer is that it avoids
memory leaks when you leave the function early, either because of a throw or
because a maintenance programmer added an early return statement. If you do
need to create an object on the stack (because you require polymorphism for
example) then scoped_ptr is better than raw pointers.
Joe Gottman