Re: Reference question
On Jan 28, 7:24 pm, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Larry.Mart...@gmail.com wrote:
I have only been working with C++ for 3 years, and I've come across
some code I don't understand.
static struct ct {
char ns, fl;
short sf;
struct st
{
char sy, fq;
ct* n;
} __attribute__ ((packed)) * sta;
st& os() const
{
return (st&) sf;
}
} __attribute__ ((packed)) *mc;
My confusion is about the os method. It appears to me that
it returns a reference to the st struct. But how does
returning sf become a reference to st?
Beats me. They are probably trying to rely on some obscure
memory layout compatibility that exists between the beginning
of the 'st' struct and a 'short'. Generally speaking a cast
like that is a VERY BAD IDEA(tm).
The key, I think, is the presence of __attribute__((packed)) all
over the place. This is obviously very platform dependent code
(and probably very low level); without knowing the exact
platform, and the context in which it occurs, we can't say any
more (and knowing all that, of course, the response would be off
topic here). Generally speaking, as you say, the cast like that
is a very bad idea, but I can imagine cases in the kernel of an
OS where it might be appropriate.
(One thing does worry me a bit---the __attribute__ is g++
syntax, so I would assume g++. And g++ generates bad code when
such casts are used, on the grounds that the results are
undefined behavior. So the "implementation defined" behavior of
what he is doing is "undefined behavior".)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34