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?