27用d编程消灭

class LifetimeObserved {
    int[] array;
    static size_t counter;//静态成员

    this() {
        array.length = 30_000;
        ++counter;
    }//结构好像没有().

    ~this() {
        --counter;
    }
}
import std.stdio;

void main() {
    foreach (i; 0 .. 20) {
        auto variable = new LifetimeObserved;
        write(LifetimeObserved.counter, ' ');
        destroy(variable);//后来加上
    }//1 2 3 4 5 6 7 8 2 3 4 
    //未执行析构
    //1 1 1 1 1 1 1 1

    writeln();

//按值传递的,生命期完,执行析构.
//按引用传递的,交给垃集.
//消灭时,指针为空针,但实体交给垃集来处理

问题是抛异常时,还未执行消灭(...),就退出区间了.
这时可用,std.typecons.scoped来代替new,其将类对象包含在结构中,这样退出区间时析构函数就调用类的析构函数了.

import std.typecons;
// ...
void main() {
    const courses = scoped!XmlElement("courses", 0);

    foreach (courseId; 0 .. 2) {
        const courseTag = "course" ~ to!string(courseId);
        const courseElement = scoped!XmlElement(courseTag, 1);

        foreach (i; 0 .. 3) {
            const gradeElement = scoped!XmlElement("grade", 2);
            const randomGrade = uniform(50, 101);

            writeln(indentationString(3), randomGrade);
        }//没有消灭()了,自动调用
    }
}
//----
import std.typecons;

class C {
    void foo() {
    }
}

void main() {
    auto p = scoped!C();
    p.foo();    //就是C,没啥区别,只是出域就退出了
}
//但不能这样:
    C c = scoped!C();//代理转为原来了,移动了,原来的实体.
    c.foo();    //出错. 
    C         a = scoped!C();    // <- 漏洞
    auto      b = scoped!C();    // <- 正确
    const     c = scoped!C();    // <- 正确
    immutable d = scoped!C();    // <- 正确
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值