Is it safe to cast between two unrelated types if their structures are similar?
This is piece of code from our team's small project (acdemic)
class B{
public:
DWORD GetLen(){return i;}
DWORD i ;
};
class A
{
public:
DWORD GetLen(){return j;}
public:
int j ;
};
B b;
b.i = 2;
A * pA = (A *)&b;
int j = pA->GetLen();
"j" will be 2. Is this code safe? Or, what should I modify it? By using rein开发者_开发百科terpret_cast or static_cast? or other thoughts?
Is this code safe?
No.
What should I do to correct it?
Remove the cast and only call member functions of A
on instances of A
.
As for what you should do instead, well, that depends entirely on what you're actually trying to do.
This code is not safe. In C++ use casting operators, e.g.: dynamic_cast
, reinterpret_cast
etc.
In this case casting is not allowed, and you're lying to the compiler.
It only works because the classes are essentially identical.
精彩评论