"Lifetime" 由 openwriter() 创建的通道变量

"Lifetime" of a channel variable created by openwriter()

以下代码是另一种尝试使用频道创建 class 的尝试。在这里,我直接从调用方传递一个通道,而不是在 class 中打开它。虽然代码给出了预期的结果,但我想知道这样做是否合法,特别是在 new 语句中直接调用 openwriter()(如 baa 的情况) .换句话说,是否可以假设只要存在引用基础文件的变量(这里 output in Myclass)文件就保持打开状态,即使实际通道变量是临时的?

class Myclass
{
    var output: channel;
    proc init( output = stdout )
    {
        this.output = output;
    }
}

proc main()
{
    var foo = new owned Myclass();
    foo.output.writeln( 10 );   // written to stdout

    var baa = new owned Myclass( openwriter("test.out") );
    baa.output.writeln( 20 );   // written to file
    baa.output.writeln( 30 );
}

我相信您的代码应该没有问题。文件和通道的文档表明它们是引用计数的,因此只要某个变量引用它们,它们就应该保持活动状态。以下引用来自 Functions for Closing Channels 上的 1.19 版文档:

Files and channels are reference counted. Each file and channel is closed automatically when no references to it remain. For example, if a local variable is the only reference to a channel, the channel will be closed when that variable goes out of scope. Programs may also close a file or channel explicitly.

是的,这应该会继续有效,因为文件和频道是引用计数的。

另见 https://chapel-lang.org/docs/modules/standard/IO.html#functions-for-closing-channels

另请注意,目前,Chapel 中的临时变量在封闭块的末尾被销毁(而不是在语句末尾,这是 C++ 所做的)。在这种情况下这无关紧要,因为在语句 var baa = ... 完成之前,通道的引用计数会在 MyClass 初始值设定项中增加。这有时会令人惊讶(参见 https://github.com/chapel-lang/chapel/issues/11492 ) and so is something we are considering adjusting (see https://github.com/chapel-lang/chapel/issues/11534)。