Re: auto_ptr
On Apr 23, 3:43 pm, DE<bumpmaster...@yahoo.com> wrote:
Ownership semantics of auto_ptr seem to make it kind of unusable in some cases?
That is correct. auto_ptr is not the correct smart pointer for many
situations.
Or at least, for now I'm mystified how you would use it.
auto_ptrs can be used in places where you want a pointer to an object,
and you want that pointer to own the memory of the object. For
instance, you are creating a local object dynamically. The auto_ptr
will help you with RAII, which simplifies correct code logic. This
can be especially nice in the presence of exceptions.
Example with a regular pointer:
void say_hi()
{
Socket * s = new Socket("192.168.0.1");
s->send("hi"); // if send throws, some resources of the Socket
won't get freed
delete s;
}
Example with an auto_ptr:
void say_hi()
{
std::auto_ptr<Socket> s(new Socket("192.168.0.1"));
s->send("hi"); // if send throws, we are insured that the
Socket's destructor will be called and then memory will be freed
// no need to call delete, we know it will be called automatically
}
Here is an example of a function that dynamically creates an object,
and wants to explicitly indicate to the caller that they now own the
object. You could do this with a standard pointer and documentation
that says "you now own this object", but an auto_ptr makes that
ownership transfer explicit in the code. Similarly scenario for
passing object ownership into a function via a parameter.
Keep in mind that ownership in this sense is "who is responsible for
cleaning up the memory of the object". Just because a pointer has
ownership to an object does not mean it is the only one with rights to
use that object.
auto_ptr<Socket> getUnusedSocket()
{
for(int address = 0; address<10; address++) // go through some
addresses
{
if(!Socket::inUse(address)) // see if any are available
{
return auto_ptr<Socket>(new Socket(address));
}
}
return auto_ptr<Socket>();
}
The truth is, shared_ptr is usually a better choice of smart pointer
because they are less likely to screw things up by deleting the object
when someone is still using it. One downside is that an
implementation of shared_ptr is probably going to be a little more
expensive (in terms of memory/CPU) than an auto_ptr. On machines
running VC and .NET, this probably isn't too much of a concern.
If you want to make a linked list with head and tail and there is only one element,
then head and tail point to the same element.
But you can't have two auto_ptr point to the same element?
Also, how do you traverse through the list without breaking the list if you use auto_ptr?
EG. walker = node.next. If you do that, next will be null and the list is broken????
I think you are understanding this correctly.
If you use shared_ptr, can you point me to some article that explains how to make sure you don't have some circular reference.
Sorry, I am not sure what you mean.