pointer-casting creates new pointer@@

With some exceptions[1], c/c++ casts operate primarily on pointers (and references). That begs the question —
Q1: does pointer casting allocate 32 bits for a new pointer (assuming 32-bit addressing)?
A: depends on context

I feel the more basic question is

Q0: does pointer initialization allocate 32 bits for a new pointer?
A: i think so:

SomeType* p2 = p1; // allocates 32 bits for a new pointer p2, unless optimized away

Now back to our original Q1, i feel casting is like a function that returns an address in a specific “context” — address returned must be used as a Type3 pointer:

(Type3) p1;

In this case, if you don’t use this address to initialize another pointer, then system doesn’t allocate another pointer. but usually you put the cast on the RHS. The LHS therefore determines whether allocation is required

Type3* p3 = (Type3) p1; // 32-bit allocated
Type3* p3=0; // this pointer could be on stack or heap
p3 = (Type3)p1; // no allocation since p3 already allocated.

As an extension of the LHS/RHS syntax, programmers also use function call syntax —

myFunction(123, (Type3)p1); // cast returns an address, to be saved in a temporary 32-bit pointer on the stack. This is more like pointer initialization.

[1] static_cast often operates on nonref variables, by implicitly invoking cvctor or OOC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s