Struct destructor

JN 666total at wp.pl
Sat Mar 2 11:32:53 UTC 2019


Compare this D code:

import std.stdio;

struct Foo
{
     ~this()
     {
         writeln("Destroying foo");
     }
}

void main()
{
     Foo[string] foos;

     foos["bar"] = Foo();
     writeln("Preparing to destroy");
     foos.remove("bar");
     writeln("Ending program");
}

and equivalent C++ code:

#include <iostream>
#include <map>
#include <string>

using namespace std;

struct Foo
{
     ~Foo()
     {
         cout << "Destroying foo" << endl;
     }
};

int main()
{
     map<string, Foo> foos;

     foos["bar"] = Foo();
     cout << "Preparing to destroy" << endl;
     foos.erase("bar");
     cout << "Ending program" << endl;
}


C++ results in:

Destroying foo
Preparing to destroy
Destroying foo
Ending program

D results in:

Preparing to destroy
Ending program
Destroying foo

Is this proper behavior? I'd imagine that when doing 
foos.remove("bar"), Foo goes out of scope and should be 
immediately cleaned up rather than at the end of the scope? Or am 
I misunderstanding how should RAII work?


More information about the Digitalmars-d-learn mailing list