Re: Raw pointers not evil after all?
On Thursday, 2 May 2013 14:20:43 UTC+1, Nobody wrote:
On Wed, 01 May 2013 16:21:03 -0700, mike3 wrote:
Be a good programmer and use what is appropriate for the task rather
than trying to form a general rule and expect magical results. I use raw
pointers, shared_ptrs, weak_ptrs, and auto_ptrs in my code.
So how should one determine which kind of pointer is appropriate for
which kind of task? For what kinds of tasks are raw pointers appropriate?
shared_ptr? weak_ptr? auto_ptr?
Raw pointers for transient references.
auto_ptr or unique_ptr where ownership is clear-cut.
Most of my uses of auto_ptr are for "temporary" ownership. The
code ends with a call of release on the auto_ptr. Except, of
course, if there is an exception (which would prevent the code
from executing to its term, at which point, the object is
managed otherwise, often by itself).
Another case where auto_ptr is appropriate is when you don't
want to be able to access the object once you've passed it on.
I use them in the interface of my interthread queues: once the
object has been posted to another thread, it cannot be accessed
by the initial thread.
shared_ptr where ownership is not clear-cut, but there can be no circular
references.
weak_ptr where you need to avoid circular references and the pointer is
not essential.
In which case, shared_ptr probably isn't the appropriate
solution.
In all cases, you need to be aware of which operations can result in
destruction (blindly using shared_ptr for even the most transient
reference isn't a practical solution).
For anything which doesn't fit the above, you need garbage collection.
Garbage collection doesn't really solve the same problems
(although some people do try to use shared_ptr as a garbage
collector). Garbage collection doesn't address object lifetime
issues, and if programmers never made mistakes, it probably
wouldn't be necessary in a C++ context (where value semantics
rule, and the only dynamically allocated objects are those which
application determined lifetimes). Since programmers aren't
perfect, however, robust applications do need garbage
collection. In order to be able to detect use of "dead"
objects: if you delete immediately, and the memory is recycled,
any use of a remaining stray pointers to the object will result
in who knows what. Garbage collection ensures that the memory
won't be recycled as long as it is reachable, so you can set an
identifiable state, check for it, and handle the error
gracefully (which may mean an assertion failure---but cannot
result in the program doing other dammage).
--
James