Hi,
Quote:
Quote:
Then inside this function, I'd need to instantiate the correct object.
But how to do it? I tried:
>
Quote:
SmartPtr<HttpResponseresp = msg;
>
Quote:
But of course doesn't work. If I were using normal pointers, then I'd
do dynamic_cast<HttpResponse*>(msg) and everything ok.
>
It doesn't work because there is no implicit conversion from
SmartPtr<HttpMsgto SmartPtr<HttpResponse>. One possible way to do it
is to create a derived class from the standard smart pointer (of
course, if you have control of the pointer implemetation, do it
directly on its implementation), and add
>
a member template function in the auto_ptr implementation, similar to
this
>
template <class NEW_T>
operator auto_ptr<NEW_T>
{
return auto_otr<NEW_T(dynamic_cast (NEW_T *(this->get ()));
>
}
Correct me if I wrong, but in that case I'd get two separate smart
pointers, wouldn't I? I'd prefer that both pointers share the
reference count, otherwise it could be very dangerous (if original
smart pointer's count reach zero, then pointer would be deleted)
Unless of course that I do a deep copy of the inner object, but that
wouldn't be performance wise..
This is what I've trying to do. I took the implementation from here,
which is simple enough and fits my purposes (at least it did before
getting here!)
http://www.josuttis.de/libbook/cont/countptr.hpp.html
And to add support for dynamic_cast I made some additions:
Added this friend function:
template<class U>
friend
CountedPtr<UDynamic_Cast(CountedPtr<T>& sp)
{
U* upcast = dynamic_cast<U*>(sp.ptr);
if (upcast)
return CountedPtr<U>(upcast, sp.count);
else
return CountedPtr<U>;
}
For this to work, I had to create a new constructor which not only
takes a pointer, but an already existing counter. This way, I avoid
what I mentioned you above.
Unfortunately, it doesn't work. I'm getting an error saying this
(using VC6)
none of the 7 overloads can convert parameter 1 from type 'const class
CountedPtr<class HttpMsg>'
Also, now I'm getting another surprise: If I have this method
void foo(const CountedPtr<HttpMsgmsg);
Then if I have an instance:
CountedPtr<HttpRequestreq(new HttpRequest);
Then I'd like to do this:
foo(req);
But it doesn't work either! Why is that? Shouldn't upcasting work?
Thanks again.