when to use of auto_ptr ???

P

Pallav singh

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
 
S

Saeed Amrollahi

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
 
J

James Kanze

Kindly let me know some place where we should use auto_ptr

Any place you need the semantics it offers. Typically, when
creating an object dynamically, to hold the pointer to the
object until whoever manages the object has control of it. Or
when you want to prevent access to the object once you've passed
it off (e.g. to another thread).
1. replace pointer class members with their corresponding
auto_ptr objects,

It's not that frequent to use an auto_ptr as a member.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top