December 18, 2013 casting between structs | ||||
|---|---|---|---|---|
| ||||
I'd like to reinterpret data as different type without copying.
extern(C) struct A{ /* */ }
struct B
{
A a;
alias a this;
}
extern(C) A* f1(){ /* */ }
B* f2()
{
return cast(B*) f1();
}
Assuming that i cast() correct state, i'd like to know if:
* it's currently safe
* it's guaranteed to be safe in the future
* there any precautions in using this pattern
Most important thing for me is a type-check, but defining operators ( since they can't be external ) would be nice too.
I'm asking because i'd like to use this pattern a lot in my code, and with my limited knowledge it's good to get some feedback of more experienced.
Ps.
In situations when i return by value instead of pointer - will memory copying be optimized away ?
| ||||
December 18, 2013 Re: casting between structs | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Mariusz `shd` Gliwiński | Mariusz `shd` Gliwiński:
> * it's currently safe
One thing to remember when casting, is that when you cast const/immutable to mutable, then you can't mutate the data.
Bye,
bearophile
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply