auto_ptr – G5 operations for a novice

An auto_ptr object wraps a heap[3] object, and deletes it judiciously. You don’t need to delete the heap object.

– If I go out of scope, I delete referent.
– release() ? detach from the referent without deletion, and hold null. A simple but important method.

– reset(p) ? delete current referent, and attach to incoming referent. see [1]. Note referent is a regular ptr, not auto_ptr

– auto_ptr as rval (ie RHS) in copier or assignment? I will hold null after ownership transfer. See [2]

– auto_ptr as lval ? delete current referent (if any), then become owner of the incoming referent, and release the RHS auto_ptr. see [1]

[1] before taking on a new referent object, I always delete current referent to avoid leak
[2] after giving up ownership, I hold null
[3] never wrap a non-heap object, or the delete() will crash

Pitfalls
! not safe as elements in containers — non-standard copier and assignment
! if you independently put the same object into 2 auto_ptr, and one of them subsequently deletes the pointee, making the other a stray dog

standard auto_ptr is a template class …

http://ootips.org/yonat/4dev/smart-pointers.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s