Hi,
see this code:
auto_ptr<int> int_auto_p(new int(3));
auto_ptr<int> int_auto_p2(int_auto_p.get());
Then, both auto_pointer will own the same object. That will violate the
single ownership expectation on auto_pointer.
Also, if i use this:
int * p = int_auot_p.get();
delete p;
Then, the object owned by auto_pointer will be removed from outside.
It's also not safe.
So, auto_pointer is not so safe.
any comments?
One approach I've seen to the general problem of managing dynamically
created objects is to create a reference counted type and an associated
pointer type that increments and decrements the reference as it is created,
assigned to, or destroyed. One example is the osg::Referenced, and the
associated osg::ref_ptr.
http://www.openscenegraph.org/documentation/
That served as much of the motivation for the code I recently posted using
the boost::intrusive_ptr<> template. There are some restrictions on how
instances of the reference counted class can be used. My class is more
restrictive than the one provied by OSG. In both cases, the destructor for
the reference counted class and all of its derivatives is protected, and
can only be accessed by a friend, or a derived class. This means objects
of this type cannot be used as automatic variables since there is an
implicit call to the destructor when the variable goes out of scope. In
the case of OSG, the osg::Referenced class makes the ref() and unref()
member functions public, thus permitting ad hoc modification of reference
counts. In the case of my util::Referenced, this is not an option. The
only way to manipulate the reference counts is through the
util::intrusive_ptr_add_ref
util::intrusive_ptr_release
I would prefer these not be publicly available, but do not see a way round
the fact that they are. In either case, the only way to destroy an object
derived from the reference counted baseclass is to decrement the reference
to 0.
This is not a perfect approach in that it leads to aforementioned
restrictions on the reference counted objects. Until the user becomes
familiar with the idiosyncracies of these classes they can be rather
difficult to work with.