Re: About reference
From: Karl Heinz Buchegger (kbuchegg_at_gascad.at)
Date: 08/11/04
- Next message: Maya: "Re: Catching exceptions thrown from base class constructors?"
- Previous message: newbiecpp: "Re: About reference"
- In reply to: newbiecpp: "Re: About reference"
- Next in thread: newbiecpp: "Re: About reference"
- Reply: newbiecpp: "Re: About reference"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 11 Aug 2004 13:52:07 +0200
newbiecpp wrote:
>
> I got more confused regarding the size of a reference. I wrote the program:
>
> char c;
> char& rc = c;
>
> struct A {
> A() : i(c) {}
> char i;
> int j;
> };
>
> int main()
> {
> std::cout << sizeof(rc) << std::endl << sizeof(A) << std::endl;
> return 0;
> }
>
> The sizeof(rc) is 1 and sizeof(A) is 8. The first looks like the reference
> doesn't have a size but the second looks like the reference just like a
> point and has a size.
How do you conclude that. In struct A there is no reference involved :-)
(I guess this is a typo in posting which also shows, that you should
always use cut&paste to copy your real code to the newsreader instead
of retyping it. I gues the above should read:
struct A {
A() : i(c) {}
char& i;
int j;
};
)
> Can someone explain this to me? I appreciate!
First of all: A reference is another name for an already existing object.
So what does that mean in practice?
It means there are situations where the compiler can do the substitution
on its own. Just like in your example for rc. The compiler tracks that
rc is just another name for c and whatever you do to rc it applies to c.
So this reference doesn't take up space in the final executable. The compiler
simply uses c whenever you write rc.
But then: The situation isn't always like this. There are situations where
the compiler doesn't know to what other object the reference is another
name for. So it has to implement the reference semantics somehow. Most
often (as far as we know: always), the compiler does this by the means
of a pointer. So in your case of the struct, the compiler puts a pointer
underneath of i and adjust the code in such a way that whenever you use
i somewhere, it dereferences that pointer.
So the conclusion is: A reference may or may not take up space in the
final executable. It all depends in which way the reference is used and
how the compiler implements things.
But for you, the programmer, all of this should not care. For you a reference
is simply: another name for an otherwise existing object. How the compiler
implements this, is none of your business.
-- Karl Heinz Buchegger kbuchegg@gascad.at
- Next message: Maya: "Re: Catching exceptions thrown from base class constructors?"
- Previous message: newbiecpp: "Re: About reference"
- In reply to: newbiecpp: "Re: About reference"
- Next in thread: newbiecpp: "Re: About reference"
- Reply: newbiecpp: "Re: About reference"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|