User forums > General (but related to Code::Blocks)
cast and static cast
Michael:
--- Quote from: rickg22 on December 09, 2005, 04:23:25 pm ---BTW, what's the difference between static_cast<type*>(pointer) and (type*)(pointer) ? I never understood it.
--- End quote ---
I must admit: I too :).
But it seems that static-cast is safer that the C style of cast. Have a look at what BS says:
http://www.research.att.com/~bs/bs_faq2.html#static-cast
Michael
Urxae:
--- Quote from: rickg22 on December 09, 2005, 04:23:25 pm ---BTW, what's the difference between static_cast<type*>(pointer) and (type*)(pointer) ? I never understood it.
--- End quote ---
--- Quote from: Takeshi Miya on December 09, 2005, 04:28:38 pm ---It is the same:
(type*)(pointer) C way
static_cast<type*>(pointer) C++ way
--- End quote ---
Sorry, not true.
--- Code: ---class A {};
class B {};
int main()
{
A a;
B b;
A* pa = &a;
B* pb1 = (B*) pa; // allowed, but don't do this
B* pb2 = static_cast<B*>(pa); // not allowed
}
--- End code ---
Michael:
--- Quote from: Urxae on December 09, 2005, 04:49:28 pm ---
--- Code: ---class A {};
class B {};
int main()
{
A a;
B b;
A* pa = &a;
B* pb1 = (B*) pa; // allowed, but don't do this
B* pb2 = static_cast<B*>(pa); // not allowed
}
--- End code ---
--- End quote ---
But you can:
--- Code: ---B* pb2 = reinterpret_cast<B*>(pa);
--- End code ---
Or?
Urxae:
--- Quote from: Michael on December 09, 2005, 05:08:59 pm ---
--- Quote from: Urxae on December 09, 2005, 04:49:28 pm ---
--- Code: ---[...]
B* pb1 = (B*) pa; // allowed, but don't do this
B* pb2 = static_cast<B*>(pa); // not allowed
[...]
--- End code ---
--- End quote ---
But you can:
--- Code: ---B* pb2 = reinterpret_cast<B*>(pa);
--- End code ---
--- End quote ---
Yes you can, that's the equivalent of the pb1 line. So in general, don't do that either ;) (but prefer it over the pb1 way if you really need to do something like this).
Michael:
--- Quote from: Urxae on December 09, 2005, 05:19:39 pm ---Yes you can, that's the equivalent of the pb1 line. So in general, don't do that either ;) (but prefer it over the pb1 way if you really need to do something like this).
--- End quote ---
Yes, I agree. I try to avoid casts, because most of the time they just bring errors difficult to find and debug. And as BS concludes in his static-cast FAQ topic...
--- Quote ---Maybe, because static_cast is so ugly and so relatively hard to type, you're more likely to think twice before using one? That would be good, because casts really are mostly avoidable in modern C++.
--- End quote ---
Navigation
[0] Message Index
[#] Next page
Go to full version