class destruction

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Sep 9 07:57:24 PDT 2015


On Wednesday, 9 September 2015 at 07:19:58 UTC, Q wrote:
> Can I be sure that the Handle is destroyed as soon as the class 
> is destroyed?

It will do that automatically.

Like the others said, you won't be sure when the class is 
destroyed unless you have the user code take ownership of it. 
(This btw is the same as C++, just in C++ the ownership syntax is 
a wee bit shorter.)

C++:

class Foo {
   public:
    Foo() { /* acquire */ }
    ~Foo() { /* destroy */ }
};

void useFoo(Foo* foo) { }

// pretend I did the header separation here

int main() {
    Foo foo;
    useFoo(&foo);
    return 0;
}


D:

--
module foo;

class Foo {
    private this() { /* acquire */ }
    ~this() { /* destroy */ }
}

struct OwnedFoo(F) {
	F foo;
	alias foo this;
	~this() {
		.destroy(foo);
	}

	@disable this(this) {}
}

auto create(F, T...)(T t) if(is(F : Foo)) {
     return OwnedFoo!F(new F(t));
}
--

--
module main;
import foo;

void useFoo(Foo foo) {}

void main() {
    auto foo = create!Foo();
}
---


The code is a bit longer since the owned pointer in the standard 
library isn't exactly what I wanted, but you could use 
std.typecons.Unique too. (Actually, it does offer a bit more 
safety in reference escaping than mine. But mine is the closest 
to C++ default).


The private constructor means it won't let you bypass the owned 
factory when creating it. A bit extra code in foo means all uses 
of it will be simple like in main.

Just don't store the reference after it is destroyed, just like 
you would need to be careful with in C++. Using the library 
Unique will help you get this right too if you want to learn that.


More information about the Digitalmars-d-learn mailing list