Re: Downcast with smart pointers?
alebcn75@gmail.com wrote:
Alf P. Steinbach's "Pointers" document:http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf
Hello, thanks for sharing that link, it looks like a nice book, I'll
give it a read.
The more I see this the more I think I'm not doing it "the right way"
May I ask you all what is the correct idiom (if there is just one..)
to do something like this?
I receive a byte stream from a network interface, so I instantiate a
generic message object:
SmartPtr<HttpMsg> msg(new HttpMsg(buffer));
When constructed, the class constructor parses the message
(generically) and then I have a message object, which is either a
request or a response (assuming there isn't any error). So here is my
problem then: given that some functionality only makes sense for
request or responses, I have to derive classes with some specific
methods:
[...]
"Once a HttpMsg..."
You can't change the type of an object. When you instantiate a HttpMsg, you
can't change the type to a HttpRequest or HttpResponse after that.
You can make a 'factory', a function that parses a buffer and gives you
either a HttpRequest or a HttpResponse:
SmartPtr<HttpMsg> createMessage(const std::string& buffer)
{
// ... parse buffer...
if (isRequest)
return SmartPtr<HttpMsg>(new HttpRequest(buffer));
else
return SmartPtr<HttpMsg>(new HttpResponse(buffer));
}
In some situations, I'd like to pass some of these objects to a
function, so assuming I have a generic function (because it could
either accept a request or response):
void foo(const SmartPtr<HttpMsg>& msg);
Then inside this function, I'd need to instantiate the correct object.
But how to do it? I tried:
SmartPtr<HttpResponse> resp = msg;
But of course doesn't work. If I were using normal pointers, then I'd
do dynamic_cast<HttpResponse*>(msg) and everything ok.
Get the raw pointer and do a dynamic_cast. Or use another smart pointer
like boost::shared_ptr (which is tr1::shared_ptr), that has a dynamic_cast
replacement: dynamic_pointer_cast<>.
Well, smart pointers transfer ownership. If your foo() function here
doesn't store the HttpMsg object, it could take a const reference instead:
void foo(const HttpMsg& msg);
--
Thomas
http://www.netmeister.org/news/learn2quote.html