Most C ++ compilers have chosen to increase compilation when trying to get sizeof(void) .
When compiling C, gcc did not match and decided to define sizeof(void) as 1. This may look strange, but it has a logical rationale. When you do pointer arithmetic by adding or removing one unit, it means adding or removing an object that points to the size. Thus, defining sizeof(void) as 1 helps to define void* as a pointer to a byte (untyped memory address). Otherwise, you would have amazing behavior using pointer arithmetic, for example p+1 == p when p is void* . Such pointer arithmetic on void pointers is not allowed in C ++, but works fine when compiling C with gcc.
The standard recommended way would be to use char* for this purpose (pointer to byte).
Another similar difference between C and C ++ when using sizeof occurs when you define an empty structure:
struct Empty { } empty;
Using gcc as my C compiler sizeof(empty) returns 0. Using g ++, the same code will return 1.
I'm not sure what the C and C ++ standards indicate at the moment, but I believe that sizing some empty structures / objects helps with link management to avoid two links to different sequential objects, the first of which is empty, get the same address. If the link is implemented using hidden pointers, as is often done, ensuring that another address helps them compare.
But this simply avoids unexpected behavior (comparing link examples) by introducing another (empty objects, even PODs consume at least 1 byte of memory).
kriss Mar 21 '13 at 9:34 2013-03-21 09:34
source share