Re: size of Empty Class
James Kanze <james.kanze@gmail.com> writes:
On Mar 13, 12:53 pm, "Marco Nef" <maill...@shima.ch> wrote:
?5.3.3/2 "The size of a most derived class shall be greater than zero"
Thank you, I found it. The reason must be arrays... I don't
like this paragraph, but it is standard.
The reason is identity, in general. If objects could have 0
size, you could end up with two different objects at the same
address.
void* p=malloc(0);
void* q=malloc(0);
assert((p!=NULL) and (q!=NULL) and (p!=q));
If C can do it with malloc, why C++ couldn't do it with classes and new?
That said, perhaps malloc(0) does allocate 1 byte behind the scene
(at least, it will allocate the overhead), and it may be simplier for
C++ implementations to have sizeof(Empty)==1; but conceptually we
don't need it, and implementation needs shouldn't transpire at the
user's level...
------------------------------------------------------------------------
#include <ciso646>
#include <iostream>
#include <cassert>
void c(){
void* p=malloc(0);
void* q=malloc(0);
assert((p!=NULL) and (q!=NULL) and (p!=q));
}
class Empty{};
class SubEmpty:public Empty{};
void cpp(){
Empty* p=new Empty();
SubEmpty* q=new SubEmpty();
std::cout<<"sizeof(*p)="<<sizeof(*p)<<std::endl;
std::cout<<"sizeof(*q)="<<sizeof(*q)<<std::endl;
assert((p!=NULL) and (q!=NULL) and (p!=q));
}
int main(){
c();
cpp();
return(0);
}
/*
-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Fri Mar 13 15:21:01
SRC="/tmp/m.c++" ; EXE="m" ; g++ -g3 -ggdb3 -o ${EXE} ${SRC} && ./${EXE} && echo status = $?
sizeof(*p)=1
sizeof(*q)=1
status = 0
Compilation finished at Fri Mar 13 15:21:02
*/
--
__Pascal Bourguignon__