Re: Never ever use a raw pointer when a smart pointer can do the same
job
On Aug 17, 5:58 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
James Kanze wrote:
On Aug 14, 5:33 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
James Kanze wrote:
On Aug 13, 6:55 pm, Noah Roberts <roberts.n...@gmail.com> wrote:
Victor Bazarov wrote:
Hicham Mouline wrote:
... my colleague says.
[...]
That's not the case in any of the applications I've worked
on. At the application level, lifetime is generally very
deterministic; objects are created and deleted as a result
of specific input from external sources. Using a
scoped_ptr, shared_ptr or an auto_ptr on any of these will
result in a double delete. (It's sometimes useful to use an
auto_ptr during the actual construction, until the
transaction has completed, or the object has been registered
wherever it has to be registered.)
All of the above allow you to delete the object explicitly.
Do they? boost::shared_ptr certainly doesn't.
#include <iostream>
#include <boost/shared_ptr.hpp>
struct test_object
{
~test_object() { std::cout << "object deleted\n"; }
};
int main()
{
boost::shared_ptr<test_object> ptr(new test_object);
ptr.reset(); // delete the object explicitly
std::cout << "post reset\n"; // to demonstrate it wasn't scope.
}
But you're not sharing anything, so it's not really an example
of using a shared_ptr; i.e. reset() will delete the object in
cases where boost::scoped_ptr would have made more sense.
The point is that in a large application, processing external
events in more or less real time (i.e. a server or a GUI), the
lifetime of most dynamically allocated objects should be
logically terminated in response to an external event---if I
have a dialog box popped up, and someone clicks on the X in the
corner, the dialog box object should cease to exist, regardless
of who has a pointer to it or not. The "correct" behavior isn't
to keep it alive until the last pointer to it disappears, but to
notify all objects which have a pointer to it (in its
destructor), so that they can get rid of the pointer (and
perhaps take additional actions).
This is a real problem, and it does result in program errors.
Using boost::shared_ptr here, however, may give a false sense of
security, but it doesn't solve the problem (and creates other
problems of its own). In all of the applications I've worked
on, we've used application specific observers---maybe some sort
of smart pointer which requires the association of an observer
would be an answer, but to date, I've not seen an implementation
of anything which really works.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34