Re: shared_ptr and nullptr
On Nov 2, 10:55 am, Greg Herlihy <gre...@mac.com> wrote:
On Oct 31, 9:48 am, Joe Gottman <jgott...@carolina.rr.com> wrote:
Consider the following program:
struct Base {};
struct Derived : public Base {};
int main() {
shared_ptr<Base> p(nullptr); // Which constructor will be called?
return 0;
}
This program will fail to compile because shared_ptr uses the following
template constructor to construct itself from pointers:
template <class Y> shared_ptr(Y *);
There are two equally valid conversions for nullptr_t: Base * or Derived
*, so the conversion from nullptr_t is ambiguous.
No, initializing a shared_ptr with a nullptr argument would always
fail - no matter whether the conversion was ambiguous or not. The type
of "T" in "T*" cannot be deduced from a nullptr argument.
Looks like the second half of my original post did not get by the
Google censors. :-) Here is the unexpurgated content:
Proposed Resolution:
Add the following constructors to 20.6.6.2:
explicit shared_ptr(nullptr_t);
template <class D> shared_ptr(nullptr_t, D d, A a);
template <class D, class A> shared_ptr(nullptr_t, D d, A a);
It seems odd to me that shared_ptr's constructor (and other methods)
would need nullptr overloads. After all, if a pointer argument's type
is not specified, wouldn't shared_ptr<T> just naturally assume that
the type is a T pointer?
So instead of a nullptr constructor overload, I suggest adding this
(more generic) constructor:
explicit shared_ptr(T* p)
that accepts not only T pointers - but also matches 0, NULL and
nullptr arguments as well. This constructor could be a "delegating"
constructor and do nothing more than call the current template
constructor - a constructor that neither a 0 or nullptr argument can
today invoke on its own.
Sunilarly, a T* overload of reset() and the other member function
would serve the same purpose. And by matching both NULL and nullptr -
these additional overloads would look both backwards - and forwards as
well.
Greg
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]