 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Rahul Guest
|
Posted: Mon Jul 10, 2006 9:10 am Post subject: static_cast vs reinterpert_cast |
|
|
Hi,
I have a
class A : public B {...member functions......data members};
and am doing the following
A *p=new A();
void *p=static_cast<void *>(p);
factory_instance->process(p);
Here p is passed to a function, which accepts void ptr. That function
need to cast it back
A *pp=static_cast<A *>(p);
The function is in the factory which accepts void *p only, the specific
implementations need to cast the pointer back to the expected class
and use it.
Question:Though both works fine, yet I want to know what is more
appropriate in this situation static_cast OR reinterpert_cast
The books suggests
static_cast=> "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cast=> To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.
But I am not able to interpret the sentences in this context  |
|
| Back to top |
|
 |
Rolf Magnus Guest
|
Posted: Thu Jul 13, 2006 9:10 am Post subject: Re: static_cast vs reinterpert_cast |
|
|
Frederick Gotham wrote:
| Quote: | Victor Bazarov posted:
Frederick Gotham wrote:
I have a simple rule-of-thumb:
If you can use static_cast, then use static_cast.
If you can't use static_cast, then use reinterpret_cast.
I have a simple preceding rule:
If you can do it without a cast, do not use any cast.
Naturally ; )
I tend to use the old-style casts now and again too, e.g.:
enum { len = 64U };
int array[len];
for(size_t i = len - 1; (size_t)-1 != i; --i)
|
I tend to use constructor-style casts in such a situation:
for(size_t i = len - 1; size_t(-1) != i; --i)
But I think that's just because C style casts look so old-style to me
now ;-)
| Quote: | Or if I need a reinterpret_cast and a const_cast at the same time:
char const *pc = 0;
int *pi = (int*)pc;
/* A very contrived example, I realise! */
|
That's an example of a situation where I would definitely go with the C++
style casts. One important advantage is that someone reading the code will
immediately see that I really intended to cast away the constness and
didn't just get it in by accident. |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|