Re: when to use of auto_ptr ???
On Oct 11, 9:03 am, Pallav singh <singh.pal...@gmail.com> wrote:
Hi
Kindly let me know some place where we should use auto_ptr
1. replace pointer class members with their corresponding auto_ptr
objects,
you fortify your constructors and other function variable
( created on stack ) against resource leaks in the
presence of exceptions, you eliminate the need to manually
deallocate resources in destructors
Thanks
Pallav Singh
Hi Pallav
std::auto_ptr is a lightweight class which wraps a raw pointer and
offers
the * and -> operators. It is based on exception safety and
Resource Acqusition is Initialization (RAII) technique. If you want to
allocate
a pointer at the begining of a scope and in any case don't worry about
deleting object
in auto_ptr:
void f()
{
int* ip = new int(10); // You have to delete at the end of scope
auto_ptr<int> ap(new int(10)); // the allocated memory is deleted
at the end of scope
// ...
delete ip;
}
If you forget to write the delete statement or in // ... part an
exception
occured, the memory allocated by ip leaks. For ap everything is OK.
Please note, auto_ptr has its own limitiations. Indeed, the auto_ptr
is not a replacement
for ordinary pointer.
FYI, in C++0x there are various kind of smart pointers: shared_ptr,
weak_ptr and unique_ptr.
They are very sophisticated and betther than auto_ptr.
See the following pages:
- The C++ Programming Language by Bjarne Stroustrup (section
14.4.2)
- http://www.research.att.com/~bs/bs_faq2.html#auto_ptr
- http://www.research.att.com/~bs/C++0xFAQ.html#std-unique_ptr
Regards,
-- Saeed Amrollahi