开发者

Structure typecast

Given the following code:

struct A_struct
{
  int x;
};

struct B_struct
{
  int y;
};

int test(A_struct some_struct)
{
  return some_struct.x;
}

B_struct B;

Can someone explain what k开发者_Python百科ind of typecasting this is?

test((A_struct&)B);

Is this essentially equivalent to:

test(*(A_struct*)&B);

I'm mainly curious in how they are equivalent, since I'm having trouble finding any text that bridges the gap.


It's a C-style cast permitting you to do some very bad things, which happens to work in this sample case since the layout in memory of the two completely unrelated structs happen to match.

Don't do this, unless you know exactly what you want and that this is how to achieve it on every platform you use.


In this case, this should be the equivalent of C++ reinterpret_cast:

5.2.10. reinterpret_cast:

An lvalue expression of type T1 can be cast to the type "reference to T2" if an expression of type "pointer to T1" can be explicitly converted to the type "pointer to T2" using a reinterpret_cast. That is, a reference cast reinterpret_cast<T&>(x) has the same effect as the conversion *reinterpret_cast<T*>(&x) with the built-in & and * operators. The result is an lvalue that refers to the same object as the source lvalue, but with a different type. No temporary is created, no copy is made, and constructors or conversion functions are not called.


test((A&)B);

is not a valid statement.

Though assuming 'B' is an instance of the struct B, the statement will blindly typecast the object B into a reference to an 'A' type of object.


Is this essentially equivalent to:

test((A*)&B);

Almost ;-P

test(*(A*)&B);

(Nasty stuff!)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜