Opened 6 months ago

Closed 6 months ago

#228 closed enhancement (fixed)

To define behaviour of new-delete on empty structs

Reported by: mlbrooks Owned by: Peter A. Buhr <pabuhr@…>
Priority: minor Component: libcfa
Version: 1.0 Keywords:
Cc:

Description

struct thing{};
void ?{}( thing & ) {
    printf("ctor\n");
}
void ^?{}( thing & ) {
    printf("dtor\n");
}

int main() {
    thing * one = new();
    delete(one);
}

Current: Outputs "ctor," but not "dtor."

An explanation of current behaviour:

  • program calls new with return type thing
  • new calls malloc with sizeof(thing), which is zero
  • malloc returns 0p when asked for zero bytes
  • new calls the thing constructor with argument *0p
  • new returns 0p as the requested object, which populates main variable one
  • program calls delete with argument one, which is 0p
  • delete of 0p is a no-op

We learned that sizeof( struct{} ) is 0 in C and 1 in C++. It is currently 0 in CFA.

One option discussed:

  • sizeof(struct{}) is 0
  • new always calls malloc, requesting min(1, sizeof(T)) bytes
  • new always calls constructor with a nonzero malloc result, except when malloc is unable to allocate
  • new skips the constructor call when malloc is unable to allocate
  • delete always calls free
  • delete does not call a destructor when the argument is 0p
  • delete calls a destructor when the argument is not 0p
  • all constructor and destructor calls use a non *0p argument

Another option discussed:

  • sizeof(struct{}) is 0
  • new always calls malloc, requesting exactly sizeof(T) bytes
  • new does not call a constructor when the type's size is nonzero and malloc returns 0p
  • new calls a constructor with argument *0p when the type's size is zero
  • delete always calls free
  • delete does not call a destructor when the type's size is nonzero and the argument is 0p
  • delete calls a destructor with argument 0p when the type's size is zero
  • constructor and destructor calls use a 0p argument for {}-structs

Change History (1)

comment:1 Changed 6 months ago by Peter A. Buhr <pabuhr@…>

Owner: set to Peter A. Buhr <pabuhr@…>
Resolution: fixed
Status: newclosed

In 0f7a0ea:

[fixes #228] delete of 0-sized object always calls destructor; always call free

Note: See TracTickets for help on using tickets.