Re: New C++ garbage collector
On Nov 1, 11:24 am, James Kanze <james.ka...@gmail.com> wrote:
Arbirary lifetime means that the lifetime of the object depends
on some external event: a request to a server, a connection, the
state of hardware, a specific user interaction, etc. When that
event occurs, the object's lifetime must end. Regardless of
whether there is a shared_ptr floating around referring to it,
or anything else.
So in the program at the end of this post, the integer pointed
to by n has "arbitrary lifetime" correct? Since the user must press
'y' to destroy it. And it would have exactly the same "arbitrary
lifetime" whether I used a naked pointer or a smart_ptr
instead of auto_ptr right?
So how is it the case that smart_ptr does not support objects
with arbitrary lifetime? Object lifetime is determined by the
/program logic/ as a whole not just the type of smart_pointer.
By the way, smart_ptr along with weak_ptr allows arbitrary lifetime
with multiple pointers that survive beyond the controlling pointer(s)
lifetime with error detection (in the form of thrown exceptions) when
a dangling weak_ptr is dereferenced.
Exactly the same level of protection from dangling pointers (though
not
automated obviously) you would have in a gc system that created
"zombie"
objects (by zeroing out memory or whatever).
<code>
#include <iostream>
#include <memory>
int main ( )
{
std::auto_ptr<int> n(new int(42)) ;
while ( std::cin ) {
char c = 0 ;
std::cout << "destroy? : " ;
std::cin >> c ;
if ( c == 'y' ) {
n.reset() ;
break ;
}
}
return 0 ;
}
</code>
KHD