Re: Smart pointer referencing its owner
On Feb 27, 4:00 am, Greg Herlihy <gre...@mac.com> wrote:
By the way, this whole scheme also fully applies to shared_ptr, and so
do the questions. That sample auto_ptr implementation is quite real,
too - at least one compiler vendor implements it that way (and does
the same to shared_ptr).
The sample code really has nothing to do with the behavior of auto_ptr
or shared_ptr. Any C++ object that attempted to delete itself in its
destructor would have the same, undefined behavior. So whether the
destructor calls "delete this" explicitly or uses a smart pointer
member variable to do so - does not make any real difference.
I see how that works for auto_ptr now, but I'm still not so sure about
shared_ptr. Again, consider the following (simplified, not thread-
safe, not deleter & weak_ptr aware, etc - I don't think all these are
relevant here) implementation of reset() for it:
T* ptr;
int* refcountptr;
void reset(T* newptr = 0) {
if (this->refcountptr && --*this->refcountptr == 0) {
delete this->ptr;
delete this->refcountptr;
}
if (this->ptr = newptr) {
this->refcountptr = new int(1);
} else {
this->refcountptr = 0;
}
}
And the client code, pretty much the same as before:
struct foo {
std::shared_ptr<foo> sp;
foo() : sp(this) {}
void reset() { sp.reset(); }
};
int main() {
(new foo)->reset();
}
In this case, there won't be "delete from destructor" for shared_ptr,
because of the check for (refcountptr == 0). But the original problem
is there - it will try to write to its own members after it's already
destructed as a member of foo. What does the Standard say in this
case?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]