Re: Smart pointer referencing its owner
Greg Herlihy wrote:
On Feb 26, 4:12 pm, Pavel Minaev <int...@gmail.com> wrote:
Consider the following (simplified) implementation of
std::auto_ptr<T>::reset():
void reset(T* newptr = 0) {
if (this->ptr && this->ptr != newptr) {
delete this->ptr;
}
this->ptr = newptr;
}
[...]
1) Is the above implementation of auto_ptr standard compliant or not;
and what is the wording in the Standard that, explicitly or
implicitly, allows it to be that way?
Here is the description of auto_ptr::reset() from the C++ Standard:
void reset(X* p=0) throw();
Effects: If get() != p then delete get().
Postconditions: *this holds the pointer p.
So, the answer is yes, the proposed implementation of auto_ptr::reset
() is conforming because it does delete the current pointer (if not
equal to p) and then stores p.
What about this alternative implementation?
void reset(T* p = 0)
{
std::swap(this->ptr, p);
if (p != this->ptr) delete p;
}
This seems to satisfy the description from the standard, but doesn't
cause an undefined behavior in the OP's case.
Maybe the standard could also allow the case by stating the conditions
in a more relaxed way, but I don't know how.
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]