Reputation: 132346
I just read
Add implicit conversion from unique_ptr<T> to T*
which focuses on the how-to-do-it part, not on should-I-do-it. I'm also not asking whether or not you think it's a good idea, but I am asking for concrete pitfalls I might stuble onto, or into, if I subclass unique_ptr
to add the functionality of implicit conversion to a raw pointer (so I could just pass it directly to functions taking pointers, without using get()
).
Upvotes: 1
Views: 218
Reputation: 137414
An implicit conversion would allow all kinds of nonsense:
{
unique_ptr<int> p(new int);
p + 10; // OK with implicit conversion
p[3]; // ditto
bool x = p; // ditto
unique_ptr<Derived> d(new Derived);
unique_ptr<Base> b(d); // OK with implicit conversion...oops
// These two unique_ptr's own the same object!
} // double deletion here
Upvotes: 3
Reputation: 9444
consider this slightly contrived case:
X* px;
{
unique_ptr<X> ux = new X;
px = ux; // implicit conversion
}
px->method();
When presented like this it is obvious that the call to px->method will fail (or not, which would be worse), but if this code were more complex (say a call to a method taking X* as a parameter, obscure bugs could go uncaught.
For example replace px = ux with a call to functionWithMemory(ux);
void functionWithMemory(X * px)
{
static X* oldX = nullptr;
if(oldX)
{
oldX->goodbye();
}
px->hello();
oldX = px;
}
still contrived, but if you keep extending this it starts to become plausible.
Upvotes: 3