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();    // <- 正确
发布了405 篇原创文章 · 获赞 25 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/fqbqrr/article/details/104588269