free causes exception

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 26 14:34:55 PST 2016


On 01/26/2016 01:21 PM, Igor wrote:

 > I allocate in a static method called New once. I then deallocate in the
 > destructor. Basically just as one would do in C++.

I would never do that in even C++. I don't know any C++ idiom that 
warrants 'delete this' where superior alternatives cannot be used.

 > class Foo
 > {
 >      ~this() // destructor for Foo
 >      {
 >          core.stdc.stdlib.free(cast(void *)this);
 >      }
 >
 >          // Creates a Foo
 >      static public Foo New()
 >      {
 >          auto buffer =
 > core.stdc.stdlib.malloc(__traits(classInstanceSize,
 > Foo))[0..__traits(classInstanceSize, Foo)];
 >          auto app = cast(Foo)emplace!Foo(buffer[]);
 >          }
 > }
 >
 > hence
 >
 > auto f = Foo.New();
 >
 > then .destroy(f);

Something else in the program must have something to do with it. I don't 
see the crash with the following program:

import std.stdio;
import core.stdc.stdlib;
import std.conv;

class Foo
{
      ~this() // destructor for Foo
      {
          core.stdc.stdlib.free(cast(void *)this);
      }

          // Creates a Foo
      static public Foo New()
      {
          auto buffer =
              core.stdc.stdlib.malloc(
                  __traits(classInstanceSize, Foo))
              [0..__traits(classInstanceSize, Foo)];
          auto app = cast(Foo)emplace!Foo(buffer[]);
          return app;
      }
}

void main() {
     auto f = Foo.New();
     .destroy(f);
}

Ali



More information about the Digitalmars-d-learn mailing list