t****n 发帖数: 15 | 1 Any one can help explaining in the following code,why pd1 points to the
start of the D object while pd2 points to the start of B subobject.
class A {/*...*/};
class B {/*...*/};
class D : public A, public B {/*...*/};
void f(B* pb)
{
D* pd1 = reinterpret_cast(pb);
D* pd2 = static_cast(pb);
}
f(new D); | t****t 发帖数: 6806 | 2 1. pd2 will point to the start of D object (new'ed in calling function), not
pd1.
2. practically speaking, the value of pd1 should be equal to pb, that is,
point to the start of B subobject. however strictly speaking, the result of
pd1 is not specified in standard. it is only known that reinterpret_cast
(reinterpret_cast(pb)) == pb.
【在 t****n 的大作中提到】 : Any one can help explaining in the following code,why pd1 points to the : start of the D object while pd2 points to the start of B subobject. : class A {/*...*/}; : class B {/*...*/}; : class D : public A, public B {/*...*/}; : void f(B* pb) : { : D* pd1 = reinterpret_cast(pb); : D* pd2 = static_cast(pb); : }
| N*********y 发帖数: 105 | 3 reinterpret_cast是強行翻譯,所以直接把pb指向的內存塊當成D*類型。reinterpret_
cast前后的內存起始地址一樣,所以pb和pb1指向同一位置。
static_cast靜態的嘗試做“合理”的翻譯。編譯器發現D是B的繼承類,并且D的起始地
址比B的起始地址相差A的大小,所以編譯器會把pb的起始地址減去A的大小來作為pd2的
地址。
【在 t****n 的大作中提到】 : Any one can help explaining in the following code,why pd1 points to the : start of the D object while pd2 points to the start of B subobject. : class A {/*...*/}; : class B {/*...*/}; : class D : public A, public B {/*...*/}; : void f(B* pb) : { : D* pd1 = reinterpret_cast(pb); : D* pd2 = static_cast(pb); : }
| t****n 发帖数: 15 | 4 Thanks thrust and NoDealToday.
Yes, that's what I thought.
But this example is given by Bjarne Stroustrup in his New Casts Revisited (
google New Casts Revisited, in the section 4). Maybe it is a typo?
not
of
*>
【在 t****t 的大作中提到】 : 1. pd2 will point to the start of D object (new'ed in calling function), not : pd1. : 2. practically speaking, the value of pd1 should be equal to pb, that is, : point to the start of B subobject. however strictly speaking, the result of : pd1 is not specified in standard. it is only known that reinterpret_cast : (reinterpret_cast(pb)) == pb.
| t****t 发帖数: 6806 | 5 i guess it's a typo.
【在 t****n 的大作中提到】 : Thanks thrust and NoDealToday. : Yes, that's what I thought. : But this example is given by Bjarne Stroustrup in his New Casts Revisited ( : google New Casts Revisited, in the section 4). Maybe it is a typo? : : not : of : *>
|
|