Hey All,
Can someone tell me what the advantages/disadvantages are for using auto_ptr?
Thanks in advance.
Printable View
Hey All,
Can someone tell me what the advantages/disadvantages are for using auto_ptr?
Thanks in advance.
Memory management.
The memory allocated by the new operator is deallocated as soon
as the pointer goes out of scope rather than you having to
remember/forget to deallocate using delete. In other words,
you don't have to remember to call delete. I'm sure there may be
other advantages but that's a start.
If you don't call delete when the pointer isn't needed anymore,
the app leaks memory and won't deallocate it until the app ends.
Code:void function()
{
int *n = new int(1);
// use n
// should call delete when finished
// delete n;
}
int main()
{
function();
// if you forget to call delete in function() then
// the memory is leaked until main is finished
}
Code:#include <memory>
void function()
{
std::auto_ptr<int> n(new int(1));
// no need to call delete
// the memory is deallocated after function
}
int main()
{
function();
}
Thanks for the reply wey97...any disadvantages?
:D
Your application will be bigger and it may run slightly slower but
it's unnoticeable. You have to understand how to USE auto_ptr
...but the advantages outweigh the disadvantages by a long shot.
There's been a lot of discussion about smart pointers that I've
really just now started to look in to. You may want to read up on
the concepts.
http://ootips.org/yonat/4dev/smart-pointers.html
Hi friend,
A good question raised!!!!
auto_ptr is a "smart pointer". It has advantages of small pointer
in memory management.
1. It do initialisation to NULL, deletes automatically.
2. It overloads to operators "*" & "->".
Problem like "Dangling pointers" dont appear because of that.
Its advisable to use it.
on Internet lots of inform. abt smart pointer available.
Bye.
Thanks to you both
And wey97, thanks for the link, I checked it out and found it very informable...
:wave:
A good compiler removes any speed or size disadvantage of simple smart pointers (such as auto_ptr) vs. careful pointer code.