I am wondering why size of object pointed by pointer is not zero even if we assigned pointer to NULL.Can anyone explain this?
compiled on g++ 4.8,ubuntu 14.04
Foo * foo=NULL;
cout<<"Size of pointed object of foo:"<<sizeof(*foo)<<endl;  //why it is not zero
                sizeof is a compile time directive. Thus, there is no run time check to see if the pointer actually points to a real object. There is no check of the pointer at all. the directive is replaced by the compiler by the size in bytes of the type, Foo in your case.
Inside sizeof we are in an unevaluated context. Any expressions inside it will never be evaluated. sizeof only cares about the type of the expression you pass it, and the type of *foo is of course Foo&. sizeof ignores the reference, so it returns the size in bytes that an object of type Foo would occupy.
Note again that the expression you wrote is never evaluated, so it does not matter whether a Foo object exists where foo points to - the value of foo (and the contents of the memory it points to) are of no relevance to sizeof.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With