【问题标题】:Is there a memory leak in this D example?这个 D 示例中是否存在内存泄漏?
【发布时间】:2014-09-14 05:43:33
【问题描述】:

来自官方 D 书:

import std.stdio;

void main()
{
    double[] slice1 = [ 1, 1, 1 ];
    double[] slice2 = [ 2, 2, 2 ];
    double[] slice3 = [ 3, 3, 3 ];

    slice2 = slice1;      // ← slice2 starts providing access
                          //   to the same elements that
                          //   slice1 provides access to

    slice3[] = slice1;    // ← the values of the elements of
                          //   slice3 change

    writeln("slice1 before: ", slice1);
    writeln("slice2 before: ", slice2);
    writeln("slice3 before: ", slice3);

    slice2[0] = 42;       // ← the value of an element that
                          //   it shares with slice1 changes

    slice3[0] = 43;       // ← the value of an element that
                          //   only it provides access to
                          //   changes

    writeln("slice1 after : ", slice1);
    writeln("slice2 after : ", slice2);
    writeln("slice3 after : ", slice3);
}

slice2是指向了一些数据,然后改成指向别的东西,这不是会导致内存泄漏吗?

【问题讨论】:

    标签: memory-leaks d


    【解决方案1】:

    D 是一种垃圾收集语言。垃圾收集器最终可能会释放分配给不可访问对象的内存。

    【讨论】:

    • 如果内存是静态分配的,GC不会释放它。但是编译器可能足够聪明,可以删除slice2 的初始分配,并让该变量直接指向slice1,因为slice2 = slice1; 直接遵循变量定义。
    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 2011-06-26
    • 2011-10-07
    • 2011-01-29
    相关资源
    最近更新 更多