E
Emmanuel Deloget
Hello y'all,
I'm currently writing a serie of blog tickets about the TR1, both from
a definition point of view and from an implementation point of view.
The next iteration in the series deals with the smart pointer sub-
library in the TR1 (weak_ptr, shared_ptr, enable_shared_from_this),
and guess what, I have a few question about the implementation of all
this.
Before I ask my question, I'd like to say that I studied all the
shared_ptr implementation I was able to study (namely,
boost::shared_ptr by Peter Dimov and the tr1 implementation of g++,
which is based on boost's implementation). Unfortunately, I still
don't understand something.
The TR1 says about the weak_ptr::expire() method:
bool expired() const;
Returns: use_count() == 0.
Throws: nothing.
[Note: expired() may be faster than use_count(). -end note]
The problems is about how it detects use_count() = 0. Let's examine
this code:
shared_ptr<A> sp(new A);
weak_ptr<A> wp(sp);
sp.reset();
This will transform sp into an empty shared_ptr. Typical
implementation will implement reset as:
void reset()
{
shared_ptr<T>().swap(*this);
}
This will destroy the pointer associated to sp (because the temp
object will go out of scope), and this will also destroy the internal
reference counter, as it is no more needed (shared_count = 0).
Question: if this internal reference counter is destroyed, how can
use_count() (and, of course) expired() be implemented so that they
don't crash?
Thanks for your patience
I'm currently writing a serie of blog tickets about the TR1, both from
a definition point of view and from an implementation point of view.
The next iteration in the series deals with the smart pointer sub-
library in the TR1 (weak_ptr, shared_ptr, enable_shared_from_this),
and guess what, I have a few question about the implementation of all
this.
Before I ask my question, I'd like to say that I studied all the
shared_ptr implementation I was able to study (namely,
boost::shared_ptr by Peter Dimov and the tr1 implementation of g++,
which is based on boost's implementation). Unfortunately, I still
don't understand something.
The TR1 says about the weak_ptr::expire() method:
bool expired() const;
Returns: use_count() == 0.
Throws: nothing.
[Note: expired() may be faster than use_count(). -end note]
The problems is about how it detects use_count() = 0. Let's examine
this code:
shared_ptr<A> sp(new A);
weak_ptr<A> wp(sp);
sp.reset();
This will transform sp into an empty shared_ptr. Typical
implementation will implement reset as:
void reset()
{
shared_ptr<T>().swap(*this);
}
This will destroy the pointer associated to sp (because the temp
object will go out of scope), and this will also destroy the internal
reference counter, as it is no more needed (shared_count = 0).
Question: if this internal reference counter is destroyed, how can
use_count() (and, of course) expired() be implemented so that they
don't crash?
Thanks for your patience