c++ - casting between two derived classes -
Is it appropriate to put between the points of the general ancestor? Does the compiler notice such a hierarchy and is it safe (call 1)? Or should the user be manually protected from the hierarchy manually (call 2)?
Say that we have
class A {}; Class B: A {}; Class C: A {Public: int SomeFunc () {return 3;}}; Int _tmain (int argc, _TCHAR * argv []) {b * b = (b *) ((a *) new c ()); // It is done manually, I believe it is safe ((C *) b) - & gt; Some finger (); // it's safe? This question has been refunded ((C *) ((A *) B)) - & gt; Some finger ();
Edit: This code is consistent and scalable
edit2: more comments added
b * b = (b *) ((a *) new c ()); // It is done manually, I believe it is safe
this no is safe. By changing the form of (t)
xp , either
static_cast
or reinterpret_cast
, speaking roughly. [Expr.cast] / 4:
- Conversions made by a
(5.2.9),const_cast
(5.2.11),- a
static_cast
followed byconst_cast
,one
li>const_cast
, >- one
reinterpret_cast
(5.2.10), or- one < Code> reinterpret_cast
Clear conversion can be done using cast notation Similar meaningful restrictions and behavior applicable [...]
If a conversion is understood in more than one of the methods listed above May be so used to explain that first appear in the list, even if the result of an interpretation of the cast is bad.
You can ignore const_cast
here because no qualification conversion has been made to your code. Both the static_cast
sufficiency in the first, first one, (A *)
, and second, (B *)
. First one is just fine. Humiliation is never an issue. The second induces another undefined behavior [Expr.static.cast] / 11:
b < / Code>, "where B
is a class type, which can be converted from" pointer to cv2 d
", where There is a valid standard conversion for "code" from D
"indicator to D
" from "indicator to b
" (4.10), if < Generated from code> B
(section 10), cv2 , cv2 , and b
There is only one CV-qualification in the form of IV-Qualification, the base class of the code of the basic base of code> D and D
[...] If type "Pointer to CV 1b "indicates the private one B
, then in fact the result of an object type D
indicates the pointer type of the pointer type D
Otherwise, the artist's result is irrelevant. Also keep in mind that because static_cast
runs UB does not mean that it is not selected (and reinterpret_cast
.)
The first and third points of the base are the first one (which causes undefined behavior), thus it is useless to talk about their validity.
Comments
Post a Comment