Re: casting A* to A& ?
From: Sigurd Stenersen (sigurds_at_utvikling.com)
Date: 10/08/04
- Next message: Sigurd Stenersen: "Re: createthread"
- Previous message: Jochen Kalmbach: "Re: createthread"
- In reply to: Agoston Bejo: "casting A* to A& ?"
- Next in thread: Agoston Bejo: "Re: casting A* to A& ?"
- Reply: Agoston Bejo: "Re: casting A* to A& ?"
- Messages sorted by: [ date ] [ thread ]
Date: Fri, 8 Oct 2004 14:09:17 +0200
Agoston Bejo wrote:
> What happens exactly when I do the following:
>
> struct A {
> int i;
> string j;
> A() {}
> };
>
> void f(A& a) {
> cout << a.i << endl;
> }
>
> int _tmain(int argc, _TCHAR* argv[])
> {
> A a;
> a.i = 6;
> A* pa = &a;
> f((A&)pa); // CRITICAL POINT
> f(*pa); // works as expected
> return 0;
> }
>
>
> How come that this is legal, anyway?
You can cast something at an address to something else at the same address.
Try doing the same cast with a constant and you'll see that that is not
allowed.
> Lately I've seen some people expect that (A&)pa be equivalent to *pa,
> which is not according to the example above.
No, it is not. *pa is a reference to whatever pa is pointing to, tho. So
f(*pa);
is perfectly fine.
> (The output for
> f((A&)pa) looks like some integer, but surely not 6 as should be if
> it meant f(*pa).)
The integer is equal to the address of a.
What actually happens is you're telling the compiler that "look here, pa is
not a pointer it's a struct of type A". That is in fact wrong, but because
you're telling the compiler that you know better it let's you do it. And
you're lucky, because the size of pa happens to be the same as the size of
an A instance. As it happens, the value of p overlaps A::i when you do the
cast.
Thus, you only get bogus results in this simple example, in reality you'd
usually get an access violation or some other hardtofind bug.
In other words, when you use a typecast, you're telling the compiler that
you know what you're doing. And that's a very silly thing to tell the
compiler if you don't know what you're doing...
(Yes, references are implemented the same way as pointers. But they have
different semantics.)
-- Sigurd http://utvikling.com
- Next message: Sigurd Stenersen: "Re: createthread"
- Previous message: Jochen Kalmbach: "Re: createthread"
- In reply to: Agoston Bejo: "casting A* to A& ?"
- Next in thread: Agoston Bejo: "Re: casting A* to A& ?"
- Reply: Agoston Bejo: "Re: casting A* to A& ?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|